GetType().GetField()运行时提示"未将对象引用设置到对象的实例"
GetType().GetField("Comp1") 监视窗口显示是空值
double Comp1 = 10; double Comp2 = 30; double Comp3 = 100;
for (int i = 0; i < 3; i++)
{
double val = (double)this.GetType().GetField("Comp" + (i + 1).ToString()).GetValue(this);
}
GetField加上BindingFlags,没传递测试了下私有的属性获取不到。示例代码如下
using System;
using System.Reflection;
namespace ConsoleApp2
{
class A
{
double Comp1 = 10;
double Comp2 = 30;
double Comp3 = 100;
public void GetValue()
{
for (int i = 0; i < 3; i++)
{
double val = (double)this.GetType().GetField("Comp" + (i + 1).ToString(), BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
Console.WriteLine(val);
}
}
}
class Program
{
static void Main(string[] args)
{
var a = new A { };
a.GetValue();
Console.ReadKey();
}
}
}
GetType().GetField("Comp1") 之后,你要判断返回值是不是null,再进行转换,
null转double能不报错吗