gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:11:20 25 4
gpt4 key购买 nike

我正在尝试列出由泛型类创建的所有运行时构造类。换句话说,如果我有一个类:

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>,...}

用例涉及一个通用分配器,它支持任何类型的对象分配(类似于 new XXX() ,但对垃圾收集器更好)。我不会详细说明,因为它只会使问题复杂化。基本上,我不会在编译时知道所有构造的类,因为该库是一个 dll,旨在与单独的代码项目一起使用。所以我需要某种形式的反射(reflection),我似乎无法在互联网上找到。

Assembly.GetExecutingAssembly().GetExportedTypes()除了基本通用类(即 typeof(GenericCls<>) )之外不包含任何内容

typeof(GenericCls<>).GetGenericArguments()仅返回类型“T”,这不仅是无效类型,而且完全没有用。

如果您只知道泛型类的类型,是否有可能找到泛型类的所有构造类? ( typeof(GenericCls<>); ) 我不确定“构造”是否是正确的词 - 我想知道当前处于事件状态的所有具体泛型派生类,或者所有这些将永远存在的类(不确定 C# 如何处理泛型构造幕后)。

最佳答案

@David Må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() 检查了它,它正在工作。快点。

关于C# 获取泛型类的所有运行时构造类的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4974653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com