您可能知道,在D语言中,我们有一种名为伏地魔类型的能力,它们被用作实现特定范围函数的内部类型:
auto createVoldemortType(int value)
{
struct TheUnnameable
{
int getValue() { return value; }
}
return TheUnnameable();
}以下是如何使用伏地魔类型:
auto voldemort = createVoldemortType(123);
writeln(voldemort.getValue()); // prints 123现在我想确认一下,这是否等同于delegate in C#?
public static void Main()
{
var voldemort = createVoldemortType(123);
Console.WriteLine(voldemort());
}
public static Func<int> createVoldemortType(int value)
{
Func<int> theUnnameable = delegate()
{
return value;
};
return theUnnameable;
} 发布于 2016-09-11 06:33:08
在C#中没有与Voldermort类型完全相同的类型。与这种本地作用域类最接近的称为匿名类型。问题是,与Voldermort类型不同,您不能在本地声明之外的编译时引用它们的静态类型:
public object SomeLocalMethod() // Must return either `dynamic` over `object`
{
var myAnonClass = new { X = 1, Y = "Hello" };
Console.WriteLine(myAnonClass.Y); // Prints "Hello";
return myAnonClass;
}
void Main()
{
object tryLookAtAnon = SomeLocalMethod(); // No access to "X" or "Y" variables here.
}但是,如果我们进入dynamic域,您可以引用基础类字段,但我们失去了类型安全性:
void Main()
{
dynamic tryLookAtAnon = SomeLocalMethod();
Console.WriteLine(tryLookAtAnon.X); // prints 1
}
public dynamic SomeLocalMethod()
{
var myAnonClass = new { X = 1, Y = "Hello" };
Console.WriteLine(myAnonClass.Y); // Prints "Hello";
return myAnonClass;
}C#中的委托类似于D级代表。它们持有对函数的引用。
https://stackoverflow.com/questions/39433430
复制相似问题