加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#获取泛型类的所有运行时构造类的列表

发布时间:2020-12-15 17:47:26 所属栏目:百科 来源:网络整理
导读:我正在尝试列出由泛型类创建的所有运行时构造的类.换句话说,如果我有一个类: public GenericClsT { public void Reset() { ... } ...} 我在这样的地方有代码: GenericClsint gci = new GenericClsint();GenericClsString gcs = new GenericClsString();Gen
我正在尝试列出由泛型类创建的所有运行时构造的类.换句话说,如果我有一个类:
public GenericCls<T> {
    public void Reset() { ... }
    ...
}

我在这样的地方有代码:

GenericCls<int> gci = new GenericCls<int>();
GenericCls<String> gcs = new GenericCls<String>();
GenericCls<float> gcf = new GenericCls<float>();
...

我可以得到这样的东西吗?

Type[] allconstructed = GetAllConstructed(typeof(GenericCls<>));

它返回{GenericCls< int>,GenericCls< String>,GenericCls< float>,…}

用例涉及一个通用的分配器,它支持任何类型的对象分配(就像新的XXX(),但更适合垃圾收集器).我不会详细说明,因为这只会使问题复杂化.基本上,我不会在编译时知道所有构造的类,因为库是一个用于单独的代码项目的DLL.所以我将需要一些形式的反思,我似乎不能在互相之间找到.

Assembly.GetExecutingAssembly().GetExportedTypes()不包含任何基类通用类(即typeof(GenericCls)))

typeof(GenericCls).GetGenericArguments()只返回类型“T”,它不仅是一个无效的类型,而且完全没用.

如果你只知道通用类的类型,是否可以找到所有构造的通用类的类? (typeof(GenericCls)))我不知道“构造”是否是正确的词 – 我想知道当前活动的所有具体的泛型派生类,或者所有这些将永远存在的(不确定) C#如何处理幕后的通用构造).

解决方法

@DavidM?rtensson:你的答案给了我一个想法.我可以在任何非泛型类中创建静态类型列表,并在构造的时候注册每个构造的类(当T已知时).
static public class ConcreteList {
    static public List<Type> concrete;
}
public class GenericCls<T> {
    static GenericCls() {
        ConcreteList.concrete.Add(typeof(GenericCls<T>));
    }
}

我用ConcreteList.concrete [x] .GetGenericArguments()检查它,它正在工作.呵呵

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读