如何将委托传递给方法,其中委托是非静态的?
我刚刚开始了解委托,我有一个实现 IDisposable 的类:
public class MyClass : IDisposable
{
public delegate int DoSomething();
public int Zero() {return 0;}
public int One() {return 1;}
public void Dispose()
{
// Cleanup
}
}
使用 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(??????????);
}
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
}
}
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
}
}
}
The actual question: how pass the Zero() function to UseMyClass method? Do I have to create an instance of MyClass (I would like to avoid this...)?
public static void main(string[] args)
{
// Call AnotherClass method, by passing Zero()
// or One() but without instatiate MyCLass
AnotherClass.UseMyClass(??????????);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的意图是该实例是由委托的调用者而不是委托的创建者提供的吗? C# 确实支持这样的未绑定委托,它称为开放委托,并且实例成为参数。
您必须使用
Delegate.CreateDelegate
来创建一个开放委托,如下所示:当然,您可以使用填充程序更轻松地做到这一点:
Is your intent that the instance is provided by the caller of the delegate, and not the creator of the delegate? C# does support such an unbound delegate, it's called an open delegate, and the instance becomes a parameter.
You have to use
Delegate.CreateDelegate
to create an open delegate, something like this:Of course, you can do it much more easily with a shim:
因为它是一个实例方法,如果你想调用它,你需要一个实例。这就是 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:
You can do the latter like this:
Then, you can call your static method like so:
没有实例化就无法完成。您可以这样做:
Cant be done without instantiation. Heres how you can do it: