is there any possibility to declare a class开发者_StackOverflow社区 dynamically? is there any possibility to create generic list with anonymous class in C#? any code snippets will help. thanks
Declaring a class dynamically requires CodeDom.
is there any possibility to create generic list with anonymous class in C#?
Yes, but it's, in general, not recommended for use outside of the immediate context. For example, this creates a generic list of an anonymous type:
var range = Enumerable.Range(0, 100);
var genericList = range.Select(value => new { Value = value }).ToList();
In the above code, genericList
is a List<T>
containing an anonymous type.
As SLaks mentioned in the comments, it is possible. But it is non-trivial. I'm not sure what you are trying to do, but you can easily add anonymous types to a generic list of objects.
List<object> list = new List<object>();
for(int i = 0; i < 10; i++){
list.Add(new { SomeProperty = i, OtherProperty = "foobar" });
}
Microsoft made C# dynamic in version 4.0. You can use the new 'dynamic' keyword. The following link has some good examples of how to use the new dynamic type.
http://msdn.microsoft.com/en-us/library/dd264741.aspx
精彩评论