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

后端 未结 7 1756
后悔当初
后悔当初 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:42

    It sounds like you could be asking one or two questions so I'll try and address them both.

    Can a class field be strongly typed to an anonymous type

    No. Anonymous type names cannot be stated in C# code (hence anonymous). The only way to statically type them is

    1. Generic type inferencee
    2. Use of the var keyword

    Neither of these are applicable to the field of a type.

    Can a class field be initialized with an anonymous type expression?

    Yes. The field just needs to be declared to a type compatible with anonymous types: object for example

    public class MyClass { 
      private static object MyProp = new {item1 = "a", item2 = "b"}; 
    } 
    

提交回复
热议问题