[英]Can delegates wrap classes in C#?
In C++ we have the std::function
type which can be used to wrap lambdas, functions and even custom classes.在 C++ 中,我们有
std::function
类型,可用于包装 lambda、函数甚至自定义类。 Here is an example of a custom class wrapped in std::function
:下面是一个用
std::function
包裹的自定义 class 示例:
#include <functional>
struct A {
void operator()() {
}
};
std::function<void()> a = A();
I though the same was possible with delegates in C# but, I can not get it to work:我虽然 C# 中的代表也可以这样做,但是我无法让它工作:
class Program
{
delegate void Foo();
class Bar
{
public void Invoke()
{
}
}
static void Main()
{
new Foo(new Bar()); // CS0149: Method name expected
}
}
I am convinced that this has to be possible somehow, because the delegate
operator internally creates a new class that inherits from System.Delegate
which suggests that I can create my own type to do the same somehow.我确信这必须以某种方式实现,因为
delegate
操作员在内部创建了一个新的 class 继承自System.Delegate
这表明我可以创建自己的类型以某种方式执行相同的操作。
Simple answer is 'no' because C# doesn't have an operator()
in the way C++ does.简单的答案是“不”,因为 C# 没有像 C++ 那样的
operator()
。
However, a lambda can be used to store not just a function, but a function on a specific object .但是,lambda 不仅可以用于存储 function,还可以用于存储特定 Z2668CFDE63131BCZ59 上的 function 。
class Program
{
delegate void Foo();
class Bar
{
public void Invoke()
{
}
}
static void Main()
{
var f = new Foo(new Bar().Invoke);
}
}
The difference is simply that in C# you have to specify the method name, rather than there being a default.区别只是在 C# 中您必须指定方法名称,而不是默认值。
Also worth noting that similarly to C++, C# has generics to help this, so we can cut out the Foo
declaration altogether:还值得注意的是,与 C++ 类似,C# 有 generics 来帮助解决这个问题,所以我们可以完全删除
Foo
声明:
var f = new Action(new Bar().Invoke);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.