C# 中的 Voldemort 类型

Voldemort types in C#

你可能知道在 D 语言中我们有一个叫做 Voldemort Types 的能力,它们被用作实现特定范围函数的内部类型:

auto createVoldemortType(int value)
{
    struct TheUnnameable
    {
        int getValue() { return value; }
    }
    return TheUnnameable();
}

伏地魔类型的使用方法如下:

auto voldemort = createVoldemortType(123);
writeln(voldemort.getValue());  // prints 123

现在我想确定一下,这是否等同于 C# 中的 delegate

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;
} 

C# 中没有确切 等价的 Voldermort 类型。最接近这种局部范围 classes 的称为匿名类型。问题是,与 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的土地,你可以参考底层class字段,但我们失去了类型安全:

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# 中的委托类似于 a delegate in D。他们持有对函数的引用。