【问题标题】:How to call a method using reflection [duplicate]如何使用反射调用方法[重复]
【发布时间】:2016-06-15 07:20:19
【问题描述】:

我如何使用反射来调用这个方法。

using System.Reflection

public static string NotSoObvius<V>(V show) where V : class
    {
        return string.Format("This is it", show);
    }

【问题讨论】:

  • 我们看不到该方法所属的类或结构。但除此之外,var res = (string)typeof(Xxx).GetMethod("NotSoObvius").MakeGenericMethod(show.GetType()).Invoke(null, new[] { show, }) 之类的东西应该没问题。
  • 注意到谢谢,但我有点不懂

标签: c#


【解决方案1】:

你应该试试这样的:

Type myType = Type.GetType("MyClass");
MethodInfo notSoObviusInfo = myType.GetMethod("NotSoObvius");
Type[] types = new Type[]{typeof(YourDesiredTypeHere)};
notSoObviusInfo = notSoObviusInfo.MakeGenericMethod(types);
string myReturn = (string)notSoObviusInfo.Invoke(null, new[]{new YourDesiredTypeHere()});

发件人:https://msdn.microsoft.com/pt-br/library/a89hcwhh(v=vs.110).aspx

【讨论】:

  • V 不是实际类型,它是方法的类型参数。所以V 不在上述范围内。并且您想使用 MakeGenericType 指定类型参数应该是什么(请参阅我对问题的评论)。而static 方法不需要“this”目标(您的magicClassObject)。所以你的答案有几个问题。
  • 你说得对。我刚刚按照 MSDN 教程修正了我的答案:msdn.microsoft.com/pt-br/library/a89hcwhh(v=vs.110).aspx“如果构造函数是静态的,则此参数必须为 null 或定义构造函数的类的实例。”
  • 答案已更新,现在一切正常!
猜你喜欢
  • 2013-02-20
  • 2018-02-18
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多