如何将委托传递给非静态委托的方法? [英] How pass delegate to a method, where delegates are non static?
本文介绍了如何将委托传递给非静态委托的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我才刚刚开始理解代表,我有一个实现IDisposable的类:
I'm just beginning understanding delegates, I have a class that implemens IDisposable:
public class MyClass : IDisposable
{
public delegate int DoSomething();
public int Zero() {return 0;}
public int One() {return 1;}
public void Dispose()
{
// Cleanup
}
}
一种方法(已定义在另一个使用MyClass的类中):
A method (defined in an another class) that is using MyClass:
public class AnotherCLass
{
public static void UseMyClass(MyClass.DoSomething func)
{
using (var mc = new MyClass())
{
// Call the delegate function
mc.func(); // <-------- this is what i should actually call
}
}
}
实际的问题:如何将Zero()函数传递给UseMyClass方法?我是否必须创建MyClass的实例(我想避免这种情况...)?
public static void main(string[] args)
{
// Call AnotherClass method, by passing Zero()
// or One() but without instatiate MyCLass
AnotherClass.UseMyClass(??????????);
}
推荐答案
由于是实例方法,如果要调用它,则需要一个实例。这就是CLR的工作原理。但是,可以使用两种选择:
Because it's an instance method, if you want to call it, you need an instance. That's simply how the CLR works. However, there are two options you could go with:
- 使成员函数保持静态。就像返回静态值一样简单,没有理由让它们成为实例方法。但是,如果确实需要实例数据...
- 使用单例实例。这样,您不必每次都创建一个新实例。想要调用您的静态方法。
- Make the member functions static. If they're as simple as returning a static value, there's no reason for them to be instance methods. However, if you do actually require instance data...
- Use a singleton instance. This way you don't need to create a new instance every time you want to call your static method.
您可以这样操作:
public class MyClass
{
private static MyClass singletonInstance;
public static MyClass SingletonInstance
{
get
{
if (singletonInstance == null)
{
singletonInstance = new MyClass();
}
return singletonInstance;
}
}
// the rest of your class implementation
}
然后,您可以像这样调用静态方法:
Then, you can call your static method like so:
AnotherClass.UseMyClass(MyClass.SingletonInstance.Zero);
这篇关于如何将委托传递给非静态委托的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文