Setting generic type at runtime

后端 未结 6 1266
无人共我
无人共我 2020-11-27 18:24

I have a class

public class A
{
   public static string B(T obj)
   {
       return TransformThisObjectToAString(obj);
   }
}

The

6条回答
  •  时光说笑
    2020-11-27 19:03

    There's absolutely support for this in the framework and the CLR - just not gracefully in C#. You can accomplish what I think you want, though, with the help of a helper method:

    public class A
    {
        public static string B(T obj)
        {
            return obj.ToString();
        }
    }
    
    public class MyClass
    {
        public static void DoExample()
        {
            Console.WriteLine(ExecuteB("Hi"));
            Console.WriteLine(ExecuteB(DateTime.Now));
        }
    
        public static object ExecuteB(object arg)
        {
            Type arg_type = arg.GetType();
            Type class_type = typeof(MyClass);
            MethodInfo mi = class_type.GetMethod("ExecuteBGeneric", BindingFlags.Static | BindingFlags.Public);
            MethodInfo mi2 = mi.MakeGenericMethod(new Type[] { arg_type });
            return mi2.Invoke(null, new object[] { arg });
        }
    
        public static object ExecuteBGeneric(T arg)
        {
            return A.B(arg);
        }
    

提交回复
热议问题