Cast to a reflected Type in C#

后端 未结 3 826
感情败类
感情败类 2021-01-31 05:15

Consider the following code:

object objFoo = MakeFoo(); // object MakeFoo(){return new Foo();}
MethodInfo methodInfo = typeof(Program).GetMethod(\"Baz\"); // Fo         


        
3条回答
  •  死守一世寂寞
    2021-01-31 05:28

    This is the first result in google about Casting to a reflected type.

    So for reference, in case sb wonders what would be a general way of casting to a reflected type:

    public static class ObjectExtensions
    {
        public static T CastTo(this object o) => (T)o;
    
        public static dynamic CastToReflected(this object o, Type type)
        {
            var methodInfo = typeof(ObjectExtensions).GetMethod(nameof(CastTo), BindingFlags.Static | BindingFlags.Public);
            var genericArguments = new[] { type };
            var genericMethodInfo = methodInfo?.MakeGenericMethod(genericArguments);
            return genericMethodInfo?.Invoke(null, new[] { o });
        }
    }
    

提交回复
热议问题