简体   繁体   中英

How to get the value of a static field in a generic class (singleton) without knowing the generic type

Ok, I try to explain my question a bit better: I have a

class DynamicTypeCreator{...}

and a method in it:

static BuildASingletonClassWithTypeBuiler<T> (T object) {...}

This method not only creates a singleton type

class Singleton01<K> {...}

but also instantiates it, defining the field

static Singleton01<K> instance = new Singleton01<K> (K object)

and another field

static Type typeOfGenericParameter = typeof(K) .

(The actual code on https://github.com/TThaan/ExtensionPropertiesForCSharp is different but that should be of no concern.)
However this method does not return the singleton type nor the instance. It's just creating them.
Plenty of times, indeed, only changing the name of the type from Singleton01 to Singleton02, Singleton03 etc and each time with a different T object as parameter.
So when I want to access one of those singletons later I don't know what object it holds and of what type it is. To get the value of any static field in eg "Singleton03" I first use

Type type = AssemblyBuilder.GetType("Singleton03") .

Trying to get a value of a static field now does not work yet, it's just null. I seem to be forced to use

Type genericType = type.MakeGenericType(new[] { typeof(T) }) .

But for this to work I already need to know the type of my parameter T object .
I want to know if there is a way to get the value of a static field in such a generic type before using .MakeGeneric() .

I found an answer now.
Since a generic class of one type is actually a different class then "the same class" of another type,
the static field in one of those classes is different from that in the other class. Therefore I can't get the value of one of those fields before using .MakeGeneric() with the fitting type.
The solution is to change the creation of my class, eg like here: Generic classes and static fields .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM