2014-01-15 20 views
0

我是新来的。我有一个问题给你,也许很简单,但我做不好。我有我的班上有几个领域:调用方法,转换

public Player player; 
public Run run; 

和代码:

public void doit(string method) 
    {   
     foreach (var prop in this.GetType().GetFields()) 
     { 
      foreach (var meth in prop.FieldType.GetMethods()) 
      { 
       if (meth.Name == method) 
       { 
        meth.Invoke(prop, null); 
       } 
      } 
     } 

但是,当我试图运行这个问题,我有一个错误运行时:

Object does not match target type.

在行:

meth.Invoke(prop, null); 

错误APPE ars,因为“prop”不是一个Class对象。

当我试图做到这一点:

Player testPlayer; 
testPlayer = prop; 

我有一个错误:

'System.Reflection.FieldInfo' to 'WindowsFormsApplication.Player'

我试过很多东西,但没有什么工作。 你能帮我吗?这对我很重要:)

谢谢。

+0

你想要做什么?也许示例输入/输出会有所帮助。 –

回答

3

您试图调用传入的实际FieldInfo对象的方法,而不是该字段的

一个简单的解决方法是:

if (meth.Name == method) 
{ 
    meth.Invoke(prop.GetValue(this), null); 
} 

不过,如果你想找到名称的方法,有一个更简单的方法:

public void doit(string method) 
{   
    foreach (var prop in this.GetType().GetFields()) 
    { 
     // Get the method by name 
     var meth = prop.FieldType.GetMethod(method); 
     if (meth != null) 
     { 
      meth.Invoke(prop.GetValue(this), null); 
     } 
    } 
} 
+0

哈哈哈! 我知道这很容易! 非常感谢! – Wowol

1

听起来像是你需要得到价值该属性:

meth.Invoke(prop.GetValue(this), null); 
相关问题