通过只知道 Class 的类型,获取 Class 的类型参数
Get the type parameter of a Class, by knowing only the Type of Class
我有一个基本抽象 class,它有一个来自另一个抽象 class 的类型参数,如:
public abstract class Database<T> where T : DatabaseItem, new() { //... }
public abstract class DatabaseItem { //... }
然后我有 children class 个固有的数:
public class ShopDatabase : Database<ShopItem> {}
public class ShopItem : DatabaseItem {}
public class WeaponDatabase : Database<WeaponItem> {}
public class WeaponItem : DatabaseItem {}
//...
现在的问题是,我有一个 Type 的 Database 数组,如:
private static readonly Type[] DATABASE_TYPES = new Type[] {
typeof (ShopDatabase),
typeof (WeaponDatabase)
};
我想将它们的所有类型参数作为另一个数组获取,如下所示:
Type[] databaseItemTypes = MyFunction (DATABASE_TYPES);
// databaseItemTypes will be an array as: [ShopDatabaseItem, WeaponDatabaseItem]
它可能与此类似 question 但我什至没有 Class 的实例,所以...
如果您要查找特定 class 的类型参数,那相对 简单:
static Type GetDatabaseTypeArgument(Type type)
{
for (Type current = type; current != null; current = current.BaseType)
{
if (current.IsGenericType && current.GetGenericTypeDefinition() == typeof(Database<>))
{
return current.GetGenericTypeArguments()[0];
}
}
throw new ArgumentException("Type incompatible with Database<T>");
}
那么你可以使用:
Type[] databaseItemTypes = DatabaseTypes.Select(GetDatabaseTypeArgument).ToArray();
请注意,如果您有 class 个:
public class Foo<T> : Database<T>
...然后您最终会得到一个 Type
引用,代表 Foo<T>
中的 T
。例如,对于基类型为 Foo<string>
的类型,摆脱它会很棘手。希望你不是那种情况...
我有一个基本抽象 class,它有一个来自另一个抽象 class 的类型参数,如:
public abstract class Database<T> where T : DatabaseItem, new() { //... }
public abstract class DatabaseItem { //... }
然后我有 children class 个固有的数:
public class ShopDatabase : Database<ShopItem> {}
public class ShopItem : DatabaseItem {}
public class WeaponDatabase : Database<WeaponItem> {}
public class WeaponItem : DatabaseItem {}
//...
现在的问题是,我有一个 Type 的 Database 数组,如:
private static readonly Type[] DATABASE_TYPES = new Type[] {
typeof (ShopDatabase),
typeof (WeaponDatabase)
};
我想将它们的所有类型参数作为另一个数组获取,如下所示:
Type[] databaseItemTypes = MyFunction (DATABASE_TYPES);
// databaseItemTypes will be an array as: [ShopDatabaseItem, WeaponDatabaseItem]
它可能与此类似 question 但我什至没有 Class 的实例,所以...
如果您要查找特定 class 的类型参数,那相对 简单:
static Type GetDatabaseTypeArgument(Type type)
{
for (Type current = type; current != null; current = current.BaseType)
{
if (current.IsGenericType && current.GetGenericTypeDefinition() == typeof(Database<>))
{
return current.GetGenericTypeArguments()[0];
}
}
throw new ArgumentException("Type incompatible with Database<T>");
}
那么你可以使用:
Type[] databaseItemTypes = DatabaseTypes.Select(GetDatabaseTypeArgument).ToArray();
请注意,如果您有 class 个:
public class Foo<T> : Database<T>
...然后您最终会得到一个 Type
引用,代表 Foo<T>
中的 T
。例如,对于基类型为 Foo<string>
的类型,摆脱它会很棘手。希望你不是那种情况...