C#中的Voldemort类型

Sir*_*ifi 7 c# closures d

正如您可能在D语言中所知,我们有一种称为Voldemort类型的能力,它们被用作实现特定范围函数的内部类型:

auto createVoldemortType(int value)
{
    struct TheUnnameable
    {
        int getValue() { return value; }
    }
    return TheUnnameable();
}
Run Code Online (Sandbox Code Playgroud)

以下是Voldemort类型的使用方法:

auto voldemort = createVoldemortType(123);
writeln(voldemort.getValue());  // prints 123
Run Code Online (Sandbox Code Playgroud)

现在我想确保,这是否等同delegate于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;
} 
Run Code Online (Sandbox Code Playgroud)

Yuv*_*kov 4

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.
}
Run Code Online (Sandbox Code Playgroud)

然而,如果我们进入 的领域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;
}
Run Code Online (Sandbox Code Playgroud)

C# 中的委托类似于D 中的委托。它们保存对函数的引用。