Javascript “var obj = new Object” Equivalent in C#

前端 未结 4 1883
别跟我提以往
别跟我提以往 2021-02-07 10:49

Is there an easy way to create and Object and set properties in C# like you can in Javascript.

Example Javascript:

var obj = new Object;

obj.value = 123         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-07 11:08

    In case, if you want to create un-tyed object use ExpandoObject.

    dynamic employee, manager;
    
    employee = new ExpandoObject();
    employee.Name = "John Smith";
    employee.Age = 33;
    
    manager = new ExpandoObject();
    manager.Name = "Allison Brown";
    manager.Age = 42;
    manager.TeamSize = 10;
    

    Your other option is to use anonymous class , but this will work for you, only if you would use it in the scope of the method, since the object type information can't be accessed from outside of the method scope.

提交回复
热议问题