简体   繁体   中英

How to pass Dynamic Class type for a Generic method in C#

I have a Generic method

JsonMapper.ToObject<>(jsonString);

but here i want to pass the Generic type to the method, which I have in a String, so how can I pass the class type from String to this methods generic type?

In java i can use

Class.forName("");

but in C# how should I do this?

There's no nice way of mixing reflection and generics; they are not friends . You could use MakeGenericMethod etc, but then you are doing a lot of things manually.

Frankly, my advice here is: don't design tools like this to use a generic API. Use a non-generic Type -based API. You can always re-expose it as generics:

public T Foo<T>(...) { return (T) Foo(typeof(T), ...); }

public object Foo(Type type, ...) {
    // the actual code
}

You can do the exact reverse - via MakeGenericMethod and Invoke - but it is less efficient and less flexible.

To get a Type from a string , see Type.GetType(string) and assembly.GetType(string) .

With something like this:

MethodInfo method = (from x in typeof(JsonMapper).GetMethods(BindingFlags.Static | BindingFlags.Public)
                     where x.Name == "ToObject" && x.IsGenericMethodDefinition
                     let pars = x.GetParameters()
                     where pars.Length == 1 && pars[0].ParameterType == typeof(string)
                     select x).Single();

// Your generic type
Type type = Type.GetType("System.String");

MethodInfo method2 = method.MakeGenericMethod(type);

// Your input
string jsonString = "Hello";

object result = method2.Invoke(null, new object[] { jsonString });

This if ToObject<> is static and has a signature like:

public static T ToObject<T>(string input)

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