简体   繁体   中英

Use variable in an anonymous type

Is it possible to use the value of a variable in an anonymous type as property name?

var foo = "bar";
var anon = new {foo = _list};
//               ^ foo should be "bar"

I hope it is clear what I'm asking for

No, it is not. You are not actually creating a dynamic object, you are creating an anonymous type. So the name of members should be known statically.If you wanna add/remove properties at runtime have a look at ExpandoObject .But still you have to specify property name like obj.bar , the way you think is not possible using dynamic either.

Edit: You have changed your question, but the answer remains.It is still not possible.You can't specify identifiers dynamically.The only way to do is creating dynamic properties at runtime using Reflection Emit .And that way you can give properties whatever name you want.But obviously this is not an ideal way and probably too much overhead for your situation. Maybe you can achieve what you want using a Dictionary but since you didn't give any information about where are you going to use this, I can't say anything for sure.

Unclear what you are asking.

In your example, you created an anonymous type with a property named foo, of the same type as _list:

var foo = "bar"; // has no effect on bellow line
var dyn = new {foo = _list}; // foo will be same type (and value) as _list

"foo" within the anonymous type is a field, foo in the outer scope is a local variable. They are two different variable references that can have the same reference value (ie point to the same variable) eg in the following example.

Perhaps you meant to do this:

var dyn = new {foo = _list};
var foo = dyn.foo;

Also, var != dynamic. var is an implicit compile time defined type, dynamic is a run time defined type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM