Can a class property/field be of anonymous type in C# 4.0?

后端 未结 7 1767
后悔当初
后悔当初 2021-01-18 02:53

As in:

public class MyClass {

  private static var MyProp = new {item1 = \"a\", item2 = \"b\"};

}

Note: The above doesn\'t compile nor wo

7条回答
  •  不思量自难忘°
    2021-01-18 03:45

    An property (or field) of a named class can't have an anonymous type, because such a type can't be referred to in code. However, an anonymous type can contain properties of anonymous type:

    var myObj = new
    {
        Foo = new { Name = "Joe", Age = 20 }
    };
    

    But such a construct has no practical use outside the local scope...

提交回复
热议问题