如何比较 FieldInfo 实例的值?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
myClass instance1 = new myClass();
myClass instance2 = new myClass();
FieldInfo[] fields = typeof(myClass).GetFields();
foreach (FieldInfo field in fields) if (field.GetValue(instance2) == field.GetValue(instance1)) Text = "Yes";
}
}
class myClass
{
public bool b = false;
public int i = 2;
}
永远不会返回“是”。
编辑:没有事先知道类型是什么。所以我不能有:(bool)field.GetValue(instance1)
。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
myClass instance1 = new myClass();
myClass instance2 = new myClass();
FieldInfo[] fields = typeof(myClass).GetFields();
foreach (FieldInfo field in fields) if (field.GetValue(instance2) == field.GetValue(instance1)) Text = "Yes";
}
}
class myClass
{
public bool b = false;
public int i = 2;
}
Never returns "Yes".
EDIT: Without knowing beforehand what the types will be. So I can't have: (bool)field.GetValue(instance1)
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在使用
==
,它将比较类型为值类型的任何字段的装箱值。每次装箱一个值时,它都会创建一个新对象,因此==
永远不会像那样工作。使用object.Equals
来代替:(这里使用静态方法意味着即使值为
null
它也能工作。)You're using
==
, which will be comparing the boxed values for any field where the type is a value type. Each time a value is boxed, it will create a new object, so==
will never work like that. Useobject.Equals
instead:(Using the static method here means it'll work even if the values are
null
.)您正在比较 FieldInfo.GetValue 返回的两个对象的
地址
,并且由于内存中的这些地址不同,因此==
永远不会成立。尝试用以下内容替换
if
:you are comparing the
address
of the two objects returned by FieldInfo.GetValue and since those addresses in memory are different, the==
is never true.try replacing the
if
with this:因为 field.GetValue(instance1) 返回值的“装箱”(对象)版本,因此调用
==
您只是比较两个不同的引用。尝试改为调用:
Because field.GetValue(instance1) returns a "boxed" (object) version of the value, hence calling
==
you are only comparing two different references.Try instead calling: