简体   繁体   中英

How to set a type dynamically into a generic method?

Say you have this generic method :

    public static T ConvertValue<T, U>(U value) where U : IConvertible
    {
        return (T)Convert.ChangeType(value, typeof(T));
    }

If I want to call this method inside another generic method. The outer generic method must receive as arguments the actual argument values to set <T, U>(U value) of the inner generic method.

How to achieve this properly, so that I can call OuterGeneric and feed it with the appropriate arguments?

This is just a demonstration of how I need to use it.

public void OuterGeneric<TypeT, TypeU>(TypeT tType, TypeU uType, TypeU valueOfTypeU)
{
   // Call of Generic method
   TypeT recieverOf_T  = ConvertValue<tType, uType>(valueOfTypeU);
}

// Some way to call OuterGeneric. How?

Just call ChangeType directly. You're wrapping the call in a method that requires the type to be specified at compile time, rather than runtime, and then asking how to call it when the type is only known at runtime. You already had a method ( ChangeType ) that does exactly that.

You don't need method parameters for the generic types in your outer method. You should be able to just use the type parameters like this:

public void OuterGeneric<TypeT, TypeU>(TypeU valueOfTypeU)
{
   // Call of Generic method
   TypeT recieverOf_T  = ConvertValue<TypeT, TypeU>(valueOfTypeU);
}

Then call OuterGeneric the way you would any other generic method.

Your question is a little unclear because you used the term "dynamically." Of course generic parameters must be known at compile time, so if you're looking for a way to use generic methods when only knowing the types at runtime, then you don't actually want to use .NET generics.

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