在C#3.0,你可以创建匿名类的语法如下如何动态创建新的匿名类?
var o1 = new { Id = 1, Name = "Foo" };
有没有一种方法来动态创建这些匿名类的变量?
例子:
var o1 = new { Id = 1, Name = "Foo" };
var o2 = new { SQ = 2, Birth = DateTime.Now };
动态创建实例:
var o1 = DynamicNewAnonymous(new NameValuePair("Id", 1), new NameValuePair("Name", "Foo"));
var o2 = DynamicNewAnonymous(new NameValuePair("SQ", 2), new NameValuePair("Birth",
DateTime.Now));
怎么一回事,因为我需要做的:
dynamic o1 = new ExpandObject();
o1."ID" = 1; <--"ID" is dynamic name
o1."Name" = "Foo"; <--"Name" is dynamic name
而且场景1:
void ShowPropertiesValue(object o)
{
Type oType = o.GetType();
foreach(var pi in oType.GetProperties())
{
Console.WriteLine("{0}={1}", pi.Name, pi.GetValue(o, null));
}
}
如果我叫:
dynamic o1 = new ExpandObject();
o1.Name = "123";
ShowPropertiesValue(o1);
它不能显示结果:
Name = 123
同时,我如何将ExpandoObject转换为AnonymouseType?
Type type = o1.GetType();
type.GetProperties(); <--I hope it can get all property of o1
最后,我修改ShowPropertiesValue()方法
void ShowPropertiesValue(object o)
{
if(o is static object) <--How to check it is dynamic or static object?
{
Type oType = o.GetType();
foreach(var pi in oType.GetProperties())
{
Console.WriteLine("{0}={1}", pi.Name, pi.GetValue(o, null));
}
}
else if(o is dynamic object) <--How to check it is dynamic or static object?
{
foreach(var pi in ???) <--How to get common dynamic object's properties info ?
{
Console.WriteLine("{0}={1}", pi.Name, pi.GetValue(o, null));
}
}
}
如何实现DynamicNewAnonymous方法或如何修改ShowPropertiesValue()?
我的动机是:
dynamic o1 = new MyDynamic();
o1.Name = "abc";
Type o1Type = o1.GetType();
var props = o1Type.GetProperties(); <--I hope can get the Name Property
如果我能勾dynamicObject的GetType方法的,并迫使转换为强类型的类型。 以上无缝代码可以正常工作。
@Vlad:我承认我对动机有点不清楚。 – 2010-09-18 01:55:29
@VladLazarenko我认为你是对的:-) – oberfreak 2011-12-01 19:02:28
请告诉我们,你想做什么以及为什么这是你选择的解决方案。 – oberfreak 2011-12-01 19:03:20