문제

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).

도움이 되었습니까?

해결책

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. Use object.Equals instead:

 foreach (FieldInfo field in fields)
 {
     if (object.Equals(field.GetValue(instance2), field.GetValue(instance1))
     {
         Text = "Yes";
     }
 }

(Using the static method here means it'll work even if the values are null.)

다른 팁

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:

if (field.GetValue(instance2).Equals(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:

field.GetValue(instance2).Equals(field.GetValue(instance1))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top