2013-03-08 478 views
3

使用類型生成器我很好地動態創建一個類型。是否有可能從匿名類型做到這一點?從一個匿名對象動態創建一個對象

我到目前爲止;

//CreateType generates a type (so that I can set it's properties once instantiated) from an //anonymous object. I am not interested in the initial value of the properties, just the Type. 
Type t = CreateType(new {Name = "Ben", Age = 23}); 
var myObject = Activator.CreateInstance(t); 

現在是否可以使用類型「t」作爲類型參數?

我的方法:

public static void DoSomething<T>() where T : new() 
{ 
} 

我想打電話給使用動態創建的「T」型這種方法。所以我可以打電話;

DoSomething<t>(); //This won't work obviously 
+0

你的意思是你構建一個匿名類型的對象,並希望得到它的類型,以創造更多的人? – Botz3000 2013-03-08 09:50:21

回答

1

是的,這是可能的。要使用類型爲類型的參數,你需要使用MakeGenericType方法:

// Of course you'll use CreateType here but this is what compiles for me :) 
var anonymous = new { Value = "blah", Number = 1 }; 
Type anonType = anonymous.GetType(); 

// Get generic list type 
Type listType = typeof(List<>); 
Type[] typeParams = new Type[] { anonType }; 
Type anonListType = listType.MakeGenericType(typeParams); 

// Create the list 
IList anonList = (IList)Activator.CreateInstance(anonListType); 

// create an instance of the anonymous type and add it 
var t = Activator.CreateInstance(anonType, "meh", 2); // arguments depending on the constructor, the default anonymous type constructor just takes all properties in their declaration order 
anonList.Add(t);