简体   繁体   中英

Passing Generic type

I have a method

 public Queryable Query<T>()
 {
 }

now can i call the method by dynamically creating generic argument T.

saomething like this

 public Queryable Query<T>()
 {

    Query<OtherT>();
 }

otherT could be a type of a property in T.

Thanks,

You can call generic methods dynamically using reflection by first getting the generic method definition (with Type.GetMethod ), then calling MakeGenericMethod and supplying the type arguments, then calling Invoke . However, you haven't given us enough information to go on in order to give you an example.

You can't. The generic parameter type needs to be known at compile time. That's why we say that when we use generics it is a strongly typed code, because the types are known in advance. When the type is known only at runtime you cannot use it as generic parameter.

Try the following:

public Queryable Query<T>()
{
    MethodInfo method = GetType().GetMethod("Query");

    return (Queryable)method.MakeGenericMethod(typeof(OtherT)).Invoke(this, null);
}

This will automatically close the Query<T> method of typeof(OtherT) . You can provide the type you require here.

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