简体   繁体   中英

If I have 2 object objects and their Type how can I get their value?

I have the following code:

Type type = typeof(T);

foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
    Type dataType = type.GetProperty(pi.Name).GetType();
    object oldValue = type.GetProperty(pi.Name).GetValue(originalVals, null);
    object newValue = type.GetProperty(pi.Name).GetValue(newVals, null);

    if (oldValue != newValue)
    {
        // Do Something
    }
}

The 2 variables originalVals and newVals that I am using are Linq2Sql classes. If 1 has an int field (intField) with an id of 999 and the other has the same field with the same value the oldValue != newValue comparison will pass because it will, obviously, use reference equality.

I'd like to know how to cast oldValue and newValue as the Type stored in dataType, something like:

((typeof(dataType)oldValue); or
(dataType)oldValue;

but this isn't working. Any suggestions?

For objects, the == and != operators just check if the references are the same: do they point to the same object?

You want to use the .Equals() method to check for value equivalence.

if (!oldvalue.Equals(newvalue))
{
    //...
}

使用if(!oldValue.Equals(newValue))if(!Object.Equals(oldValue, newValue))代替!=

You can check if they implement the IComparable interface and use that to do the comparison.

IComparable comparable = newValue as IComparable;
if(comparable.CompareTo(oldValue) != 0)
{
    //Do Stuff
}

Try:

Convert.ChangeType(oldValue, dataType)

This should cast oldValue to the type represented by dataType .

I think you need to do this first of all

Type dataType = type.GetProperty(pi.Name).PropertyType;

This will give you the type of the data for the property. What you have is getting you a type for the instance of PropertyInfo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM