25

私は持っている:

class Car {..}
class Other{
  List<T> GetAll(){..}
}

私はやってみたいです:

Type t = typeof(Car);
List<t> Cars = GetAll<t>();

これどうやってするの?

リフレクションを使用して、実行時に発見した型のデータベースからジェネリック コレクションを返したいと考えています。

4

2 に答える 2

26
Type generic = typeof(List<>);    
Type specific = generic.MakeGenericType(typeof(int));    
ConstructorInfo ci = specific.GetConstructor(Type.EmptyTypes);    
object o = ci.Invoke(new object[] { });
于 2009-02-05T00:10:47.560 に答える
8

これにはリフレクションを使用できます。

Type t = typeof(Car);
System.Type genericType= generic.MakeGenericType(new System.Type[] { t});
Activator.CreateInstance(genericType, args);
于 2009-02-05T00:11:32.647 に答える