C# 调用方法,转换
我是新来的。我有个问题要问你,也许很简单,但我做不好。我班上有几个字段:C# 调用方法,转换,c#,C#,我是新来的。我有个问题要问你,也许很简单,但我做不好。我班上有几个字段: public Player player; public Run run; 和一个代码: public void doit(string method) { foreach (var prop in this.GetType().GetFields()) { foreach (var meth in prop.FieldType.
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);
}
}
}
但当我试图运行此问题时,运行时出现错误:
对象与目标类型不匹配
一致:
meth.Invoke(prop, null);
出现错误,因为“prop”不是类对象
当我尝试这样做时:
Player testPlayer;
testPlayer = prop;
我有一个错误:
“System.Reflection.FieldInfo”到“WindowsFormsApplication.Player”
我尝试了很多东西,但都不管用。
你能帮我吗?这对我很重要:)
谢谢。您试图调用传入实际
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);
}
}
}
您试图调用传入实际
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);
}
}
}
听起来您需要获取该属性的值:
meth.Invoke(prop.GetValue(this), null);
听起来您需要获取该属性的值:
meth.Invoke(prop.GetValue(this), null);
你想干什么?也许示例输入/输出会有所帮助。您想做什么?也许示例输入/输出会有所帮助。哈哈哈!我知道这很容易!谢谢!哈哈哈!我知道这很容易!谢谢!