如何隐式转换上反射的方法调用 [英] How to cast implicitly on a reflected method call

查看:140
本文介绍了如何隐式转换上反射的方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类的事情即从字符串隐含浇注料。当我打电话了的事情参数直接从铸字符串的方法来的事情正确完成。

I have a class Thing that is implicitly castable from a string. When I call a method with a Thing parameter directly the cast from string to Thing is done correctly.

但是,如果我使用反射来调用它抛出异常

However if I use reflection to call the same method it throws the exception

System.ArgumentException : Object of type 'System.String' cannot be 
converted to type 'Things.Program+Thing'.



也许有这个一个很好的理由,但我无法弄清楚。是否有人有一个想法如何得到这个使用反射的工作?

Maybe there is a good reason for this, but I can't figure it out. Does somebody have an idea how to get this working using reflection?

namespace Things
{
    class Program
    {
        public class Thing
        {
            public string Some;

            public static implicit operator Thing(string s)
            {
                return new Thing {Some = s};
            }
        }

        public void showThing(Thing t)
        {
            Console.WriteLine("Some = " + t.Some);
        }

        public void Main()
        {
            showThing("foo");
            MethodInfo showThingReflected = GetType().GetMethod("showThing");
            showThingReflected.Invoke(this, new dynamic[] {"foo"});
        }
    }
}



元:请,不讨论为什么隐式转换或反射是坏的。

推荐答案

发现它使用的TypeConverter(如赛义德答案提到)

似乎做这项工作。

Found an answer which uses a TypeConverter (as Saeed mentions)
Seems to do the job.

TypeConverter的隐式转换使用

这篇关于如何隐式转换上反射的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆