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

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

    In C# 7 you can finally do this:

    private (string Login, string Password) _credentials = (Login: "123", Password: "123");
    
    0 讨论(0)
  • 2021-01-18 03:37

    No, anonymous types cannot be exposed outside of their declaring function as anything other than object. While the anonymous type is just syntactical sugar and does, in fact, create a concrete type, this type is never known (nor available) to the developer, and thus can't be used.

    0 讨论(0)
  • 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"}; 
    } 
    
    0 讨论(0)
  • 2021-01-18 03:44

    If this is C# 4, look into the dynamic keyword.

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

    However, as soon as you do this you lose any sort of type-safety and handy compiler checks.

    0 讨论(0)
  • 2021-01-18 03:44

    How about using Tuple<string, string> instead?

    public class MyClass {
    
      private static Tuple<string, string> MyProp = Tuple.Create("a", "b");
    
    }
    
    0 讨论(0)
  • 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...

    0 讨论(0)
提交回复
热议问题