开发者

Can I dynamically create a property type and property name for an object?

Can I dynamically create a property type and property name for an (anonymous) object if the name and type I get from a string variable开发者_运维知识库?


If you're talking about anonymous types (such as var x = new { Property1 = data1, ...}) then I don't think that you can.

What you might be able to do is create another new anonymous type from the one you already have. Where you want to create Y from X, you could create Y by var Y = new { YProp1 = X.Prop1, YProp2 = X.Prop2, etc}


In c# 4.0 onwards you can use dynamic keyword with DynamicObject object based on dictionary to create/extend properties at runtime very much like JavaScript.


For anonymous classes, no. These are defined at compile-time by the compiler.


C# .NET is a statically typed language, meaning that all classes must be defined at compile time. So, the knee-jerk answer to your question is no.

However, like most languages, there are workarounds that you can use. For instance, you can create a class that has a Dictionary<string,object> type property that will take your property names as keys and your property values as values.

Of course, the downside to this is that you will need to write extra code to verify that the data in the dictionary is valid... so it may not be worth it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜