Get a List of Generic Types Applied to Any Class
I have a particular need which I cannot seem to figure out. I've done some research into this, but cannot find a feasible solution.
I have a base class:
public abstract class BaseProvider<T> {}
this class in turn is inherited by two different provider classes:
public sealed class MonkeyProvider<T>
: BaseProvider<MonkeyProvider<T>>
where T
: IAnimalProvider
Within in the interface IAnimalProvider I expose a single property that all implementations must derive off. Now, MonkeyProvider and maybe DonkeyProvider or something similar needs to know what the as开发者_C百科signed value for the property the root instance is:
public class JoburgZoo
: IAnimalProvider
{
#region IAnimalProvider members
public string Id{ get; set; }
#endregion
}
// somewhere in a console application
public static void Main(string[] args)
{
JoburgZoo zoo = new JoburgZoo();
zoo.Id = "Mammals";
**// edit: an instance of the provider will be created**
MonkeyProvider<JoburgZoo> mp = new MonkeyProvider<JoburgZoo>();
mp.CheckMonkeys(zoo); // where CheckMonkeys(JoburgZoo) is a method in the provider
}
Now, here is my actual question:
I have the need to expose an internal property through BaseProvider which every instance that implement it, has access to. This property needs to return the value of "Id" at any given point, but I cannot seem to be able get the value through reflection (which I know is the solution to this).
From my various fruitless efforts:
Type type = typeof(T); // this returns BaseProvider<MonkeyProvider<T>>
var generic = type.GetGenericTypeDefinition(); // brings back BaseProvider<T>
I can't create a new instance of T as it will clear all values currently assigned to the object. I can't iterate the property info collection, as that will only return the properties of BaseProvider.
Thanks for any help on this. Eric
// Edit.
Added an additional call in the console main code above. the instance of MonkeyProvider<T>
templates JoburgZoo, so in ProviderBase<T>
it will look something like:
ProviderBase<MonkeyProvider<JoburgZoo>>
I want to know what the properties of JoburgZoo is, from within the BaseProvider<T>
without the need to identify the object withing MonkeyProvider<T>
.
Hope this makes sense.
With following class definition,
class BaseProvider<T>
{
//...
}
following code returns System.Int32
:
Type type = typeof(BaseProvider<Int32>);
foreach (var arg in type.GetGenericArguments())
{
MessageBox.Show(arg.FullName);
}
精彩评论