简体   繁体   中英

Strange float behavior

var v1 = propertyInfo.GetValue(actor);
var v2 = propertyInfo.GetValue(blueprint);

bool isActorValueSame = v1 == v2;       

Whenever I try to compare v1 and v2 - I receive false boolean even though both v1 and v2 are equal to 500.0f. Any ideas why this is happening? I understand that it's not safe to compare two floats, because of float inaccuracy, but I have values that both are 100% equal.

Because propertyInfo.GetValue(blueprint); will return object and object is reference type so equal operator would always get you false. try casting before comparison

var v1 = (float)propertyInfo.GetValue(actor);
var v2 = (float)propertyInfo.GetValue(blueprint);

bool isActorValueSame = v1 == v2; 

Have a look at MSDN documentation here for more detail on PropertyInfo.GetValue method

As written by Jenish... Addendum:

var v1 = propertyInfo.GetValue(actor);
var v2 = propertyInfo.GetValue(blueprint);

bool isActorValueSame = v1.Equals(v2);

This will work, because the Object.Equals :

For value types, equality is defined as bitwise equality

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