开发者

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))
{
    //...
}


use if(!oldValue.Equals(newValue)) or if(!Object.Equals(oldValue, newValue)) instead of !=


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜