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

2019-03-18 03:07发布

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 = 123476;
obj.description = "this is my new object";
obj.mode = 1;

4条回答
淡お忘
2楼-- · 2019-03-18 03:27

try c# anonymous classes

var obj = new { 
    value = 123475, 
    description = "this is my new object", 
    mode = 1 };

there are lots of differences though...

@Valera Kolupaev & @GlennFerrieLive mentioned another approach with dynamic keyword

查看更多
够拽才男人
3楼-- · 2019-03-18 03:36

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-03-18 03:45

The way to do this is you use C# 4.0 Dynamic types like Expando Object... see this topic:

How to create a class dynamically

查看更多
成全新的幸福
5楼-- · 2019-03-18 03:50

In C# you could do:

var obj = new SomeObject {
    value = 123476,
    description = "this is my new object",
    mode = 1
};

EDIT: Holding this here pending clarification from OP as I may have misunderstood his intentions.

查看更多
登录 后发表回答