In C# 3.0 können Sie anonyme Klasse mit folgenden Syntax erstellenWie dynamisch neue anonyme Klasse?
var o1 = new { Id = 1, Name = "Foo" };
Gibt es eine Möglichkeit, um dynamische diese anonyme Klasse zu einer Variablen zu erstellen?
Beispiel:
var o1 = new { Id = 1, Name = "Foo" };
var o2 = new { SQ = 2, Birth = DateTime.Now };
Dynamische erstellen Beispiel:
var o1 = DynamicNewAnonymous(new NameValuePair("Id", 1), new NameValuePair("Name", "Foo"));
var o2 = DynamicNewAnonymous(new NameValuePair("SQ", 2), new NameValuePair("Birth",
DateTime.Now));
Beacuse ich tun muss:
dynamic o1 = new ExpandObject();
o1."ID" = 1; <--"ID" is dynamic name
o1."Name" = "Foo"; <--"Name" is dynamic name
Und Scene1:
void ShowPropertiesValue(object o)
{
Type oType = o.GetType();
foreach(var pi in oType.GetProperties())
{
Console.WriteLine("{0}={1}", pi.Name, pi.GetValue(o, null));
}
}
wenn ich rufe:
Name = 123
ich, wie zu konvertieren und auch die ExpandoObject zu AnonymouseType:
dynamic o1 = new ExpandObject();
o1.Name = "123";
ShowPropertiesValue(o1);
Es ist nicht das Ergebnis zeigen kann?
Type type = o1.GetType();
type.GetProperties(); <--I hope it can get all property of o1
Last, ich ShowPropertiesValue() -Methode
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));
}
}
}
Wie implementieren DynamicNewAnonymous Methode oder wie die ShowPropertiesValue ändern() ändern?
Meine Motivation ist:
dynamic o1 = new MyDynamic();
o1.Name = "abc";
Type o1Type = o1.GetType();
var props = o1Type.GetProperties(); <--I hope can get the Name Property
Wenn i dynamic der GetType-Methode kann Haken und Compel konvertieren Typ-stark typisiert. Der obige Seamless-Code kann gut funktionieren.
@Vlad: Ich gebe zu, ich bin ein wenig unklar über die Motivationen. –
@VladLazarenko Ich denke, du hast recht :-) – oberfreak
Bitte sag uns, was du machen willst und warum dies deine ausgewählte Lösung ist. – oberfreak