Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
750 views
in Technique[技术] by (71.8m points)

properties - Dynamically set the property name of a C# anonymous type

Is there any way to dynamically set the property name of an anonymous type?

Normally we'd do like this:

var anon = new { name = "Kayes" };

Now I'd like to set the name (or identifier) of the property dynamically, so that this name can come from an XML file or a database.


Thanks guys for your answers. No, my need is definitely not worth all the tedious alternatives. I just wanted to make my code comply with an existing library that was developed by my team lead. But we decided to update the library to support Dictionary types so that it can easily be solved.

Pete, I'm really excited to learn about dynamic types in .NET 4.0

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That is not possible because even though the type is anonymous, it is not a dynamic type. It is still a static type, and properties about it must be known at compile time.

You might want to check out the .NET 4.0 "dynamic" keyword for generating true dynamic classes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...