使用类型构建器我可以动态创建类型。是否可以从匿名类型执行此操作?
到目前为止,我有这个;
//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);
现在可以使用Type“t”作为类型参数吗?
我的方法:
public static void DoSomething<T>() where T : new()
{
}
我想使用动态创建的Type“t”来调用此方法。所以我可以打电话;
DoSomething<t>(); //This won't work obviously
答案 0 :(得分: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);