从静态方法C#调用非静态方法 [英] Call non-static method from static method c#
问题描述
可能重复:结果
的通话从静态方法C#
我们还可以从静态方法创建实例,非静态方法。代码:
We can call non-static method from static method creating instance. Code:
public class Foo
{
public void Data1()
{
}
public static void Data2()
{
Foo foo = new Foo();
foo.Data1();
}
}
不过,听说非静态方法可以从代表的帮助下静态方法调用。是真的吗?如果是,那么如何?请指导我的示例代码。谢谢你。
However, I heard that non-static method can be called from static method with the help of delegate. is it true? If yes, then how? Please guide me with sample code. Thanks.
推荐答案
这是调用通过委托的非静态方法的方法。请注意,它是一个两步骤的过程中,由于到呼叫非静态方法,绝对需要的类的一个实例。我还要指出,有几乎可以肯定是一个更好的方式做你想做的事,因为的需要的调用从静态方法非静态方法尽管没有想用一个对象实例使听起来像非静态方法应该是静态的。
This is one method for calling a non-static method via a delegate. Note that it is a two-step process, since to call a non-static method, you absolutely need an instance of the class. I would also note that there is almost certainly a better way to do what you want to do, since needing to call a non-static method from a static method despite not wanting to use an object instance makes it sound like the non-static method should be static.
public class MyClass
{
private static Action NonStaticDelegate;
public void NonStaticMethod()
{
Console.WriteLine("Non-Static!");
}
public static void CaptureDelegate()
{
MyClass temp = new MyClass();
MyClass.NonStaticDelegate = new Action(temp.NonStaticMethod);
}
public static void RunNonStaticMethod()
{
if (MyClass.NonStaticDelegate != null)
{
// This will run the non-static method.
// Note that you still needed to create an instance beforehand
MyClass.NonStaticDelegate();
}
}
}
这篇关于从静态方法C#调用非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!