Is it possible to create an object without a class in C#?

久未见 提交于 2020-06-25 07:29:18

问题


In many languages you can create an object without creating a data type, and add properties to that object.

For example in JS or AS:

 var myObject = {};
 myObject.myParameter = "hello world";

Or you can create structures in C and C++.

Is it possible to do that in C#?


回答1:


Yes there is ExpandoObject under System.Dynamic namespace.You could add properties on the fly like you do in other dynamic languages

dynamic dynObject = new ExpandoObject();
dynObject.someProperty= "Value";

http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx




回答2:


Anonymous Types is what you looking for. Eg -

var v = new { Amount = 108, Message = "Hello" };

Above code will create a new object with properties Amount and Message.




回答3:


Read about ExpandoObject

dynamic myObject = new ExpandoObject();
myObject.myParameter = "hello world";

Console.WriteLine(myObject.myParameter);



回答4:


C# 9 coming up with new feature , you can create object without new now https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#target-typed-new-expressions

new expressions in C# have always required a type to be specified (except for implicitly typed array expressions). Now you can leave out the type if there’s a clear type that the expressions is being assigned to.

Point p = new (3, 5);


来源:https://stackoverflow.com/questions/13000648/is-it-possible-to-create-an-object-without-a-class-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!