Non-read only alternative to anonymous types

前端 未结 6 1513
误落风尘
误落风尘 2020-11-29 09:02

In C#, an anonymous type can be as follows:

method doStuff(){
     var myVar = new {
         a = false, 
         b = true
     }

     if (myVar.a) 
     {         


        
6条回答
  •  -上瘾入骨i
    2020-11-29 09:28

    No, you'll have to create your own class or struct to do this (preferrably a class if you want it to be mutable - mutable structs are horrible).

    If you don't care about Equals/ToString/GetHashCode implementations, that's pretty easy:

    public class MyClass {
        public bool Foo { get; set; }
        public bool Bar { get; set; }
    }
    

    (I'd still use properties rather than fields, for various reasons.)

    Personally I usually find myself wanting an immutable type which I can pass between methods etc - I want a named version of the existing anonymous type feature...

提交回复
热议问题