通过仅了解类的类型来获取类的类型参数 [英] Get the type parameter of a Class, by knowing only the Type of Class

查看:51
本文介绍了通过仅了解类的类型来获取类的类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基础抽象类,它具有另一个抽象类的类型参数,例如:

I have a base abstract class having a type parameter from another abstract class, as:

public abstract class Database<T> where T : DatabaseItem, new() { //... }

public abstract class DatabaseItem { //... }

然后我有一些固有的子类:

Then I have number of children classes inherent from it:

public class ShopDatabase : Database<ShopItem> {}
public class ShopItem : DatabaseItem {}

public class WeaponDatabase : Database<WeaponItem> {}
public class WeaponItem : DatabaseItem {}

//...

现在的问题是,我有一个数据库 Type 数组:

Now the problem is, I have an array of Type of Database as:

private static readonly Type[] DATABASE_TYPES = new Type[] {
    typeof (ShopDatabase),
    typeof (WeaponDatabase)
};

我想将所有类型参数作为另一个数组获取,像这样:

And I want to get all their type parameters as another array, something like this:

Type[] databaseItemTypes = MyFunction (DATABASE_TYPES);
// databaseItemTypes will be an array as: [ShopDatabaseItem, WeaponDatabaseItem]

它可能类似于以下问题但我什至没有Class的实例,所以...

It may be similar to this question but I don't even have a instance of the Class, so...

推荐答案

如果您要查找特定类的类型参数,那么相对容易:

If you're looking for the type arguments for a specific class, that's relatively easy:

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();

请注意,如果您有以下课程:

Note that if you have a class of:

public class Foo<T> : Database<T>

...然后您将最终获得一个 Type 引用,该引用表示 Foo< T> 中的 T .例如,对于基本类型为 Foo< string> 的类型,要摆脱这种情况将很棘手.希望你不在那种情况下...

... then you'll end up getting a Type reference representing the T in Foo<T>. Getting rid of that for a type with a base type of Foo<string> for example would be tricky. Hopefully you're not in that situation...

这篇关于通过仅了解类的类型来获取类的类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆