[英]C# Get a list of all runtime constructed classes of a generic class
I'm trying to make a list of all the runtime constructed classes created by a generic class. 我试图列出由通用类创建的所有运行时构造类。 In other words, if I have a class: 换句话说,如果我有课:
public GenericCls<T> {
public void Reset() { ... }
...
}
And I have code in various places like this: 我在这样的不同地方都有代码:
GenericCls<int> gci = new GenericCls<int>();
GenericCls<String> gcs = new GenericCls<String>();
GenericCls<float> gcf = new GenericCls<float>();
...
Can I get something like this?: 我可以得到这样的东西吗:
Type[] allconstructed = GetAllConstructed(typeof(GenericCls<>));
which returns {GenericCls<int>,GenericCls<String>,GenericCls<float>,...}
返回{GenericCls<int>,GenericCls<String>,GenericCls<float>,...}
The use case involves a generic allocator, that supports any type of object allocation (it's like new XXX()
, but nicer to the garbage collector). 该用例涉及一个通用分配器,该分配器支持任何类型的对象分配(就像new XXX()
,但是比垃圾收集器更好)。 I won't go into specifics, because it will just complicate the question. 我不会详细说明,因为这只会使问题复杂化。 Basically, I will not know all the constructed classes at compile time, since the library is a dll intended to be used with a separate code project. 基本上,在编译时我不会知道所有构造的类,因为该库是旨在与单独的代码项目一起使用的dll。 So I will need some form of reflection that I can't seem to find on the interwebs. 因此,我将需要某种形式的反射,这些反射似乎是在互连网上找不到的。
Assembly.GetExecutingAssembly().GetExportedTypes()
does not contain anything but the base generic class (ie typeof(GenericCls<>)
) Assembly.GetExecutingAssembly().GetExportedTypes()
除了基本的通用类(即typeof(GenericCls<>)
)之外,不包含任何内容。
typeof(GenericCls<>).GetGenericArguments()
returns only Type "T", which is not only an invalid type, but entirely useless. typeof(GenericCls<>).GetGenericArguments()
仅返回类型“ T”,它不仅是无效类型,而且完全无用。
Is it even possible to find all constructed classes of a generic class if you only know the generic class' type? 如果仅知道通用类的类型,是否甚至可以找到通用类的所有构造类? ( typeof(GenericCls<>);
) I'm not sure if "constructed" is the right word - I want to know either all the concrete generic-derived classes currently active, or all of these that will ever exist (not sure how C# handles generic construction behind the scenes). ( typeof(GenericCls<>);
)我不确定“ constructed”是否是正确的词-我想知道当前活动的所有具体泛型派生类,还是所有将存在的类(不确定如何C#在后台处理通用构造)。
@David Mårtensson: Your answer gave me an idea. @DavidMårtensson:您的回答给了我一个主意。 I could make a static list of types in any non-generic class, and register each constructed class as it was constructed (when T is known). 我可以在任何非泛型类中列出类型的静态列表,并在构造时注册每个构造的类(当已知T时)。 ie 即
static public class ConcreteList {
static public List<Type> concrete;
}
public class GenericCls<T> {
static GenericCls() {
ConcreteList.concrete.Add(typeof(GenericCls<T>));
}
}
I checked it with ConcreteList.concrete[x].GetGenericArguments()
, and it's working. 我用ConcreteList.concrete[x].GetGenericArguments()
,它正在工作。 Oh snap. 哦,快点
您可以使用工厂类来创建实例,这样工厂类可以保留所有已创建类的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.