How to create a generic type to match another generic method

I have a method in class A

public IList<T> MyMethod<T>() where T:AObject 

I want to call this method in another generic class B. This is T without any restrictions.

 public mehtodInClassB(){ if (typeof(AObject)==typeof(T)) { //Compile error here, how can I cast the T to a AObject Type //Get the MyMethod data A a = new A(); a.MyMethod<T>(); } } 

Class C inherits from class AObject.

 B<C> b = new B<C>(); b.mehtodInClassB() 

any thoughts?

After the urs remind ... Update:

Yes. I really want to do

 typeof(AObject).IsAssignableFrom(typeof(T)) 

not

 typeof(AObject)==typeof(T)) 
+7
source share
2 answers

If you know that T is an AObject , why not just specify AObject as a parameter of type MyMethod :

 if (typeof(AObject).IsAssignableFrom(typeof(T))) { //Compile error here, how can I cast the T to a AObject Type //Get the MyMethod data d.MyMethod<AObject>(); } 

If providing AObject as a type parameter is not a parameter, you will have to put the same restrictions on T in the calling method:

 void Caller<T>() where T: AObject { // ... d.MyMethod<T>(); // ... } 
+7
source

You cannot do this unless you place the same restriction on the contained method. Generics are checked at compile time, so you cannot make such runtime decisions.

Alternatively, you can use reflection to call a method, it just requires a bit more code.

See this SO question for more information on how to do this: How to use reflection to invoke a generic method?

+1
source

All Articles