简体   繁体   中英

C# get property value with reflection has not default value

I have this code:

messageDto = new CorrelationDto()
{
timestamp = default,
};

var isDefault = messageDto.GetType().GetProperty("timestamp").GetValue(messageDto) == default; // FALSE
var isDefault2 = messageDto.timestamp == default; // TRUE

where timestamp is a DateTime.

As you can see, getting the value through reflection and comparing to default return false. Do you have any idea why it's happening and how should I do to check for default values? Thanks

== EDIT ==

It has been pointed to me that the return value of GetValue() is an object and so it must be casted to DateTime in order for the default to work. Unfortunately I cannot because I'm running this test on all the properties of an object to discover if this object is initialized or not (so I check for null or default value). And the messageDto in reality is a generic type so I don't know the types of its properties a priori.

GetValue returns an object of type object , because it can't know at compile time what the type of the property is. The default value of an object is null , but since DateTime is a value type, its default value cannot be null .

Cast the result of GetValue to DateTime .

If I correctly understood you, this is how I solved this problem:

    private static bool IsValueNumericDefault(object value)
    {
        var intVal = 1;
        var doubleVal = 1.0;

        return (int.TryParse($"{value}", out intVal) || double.TryParse($"{value}", out doubleVal)) && 
               (intVal == default || doubleVal == default);
    }

I check random object value through casting it to string and try parse to type that I check. Value parameter is returned by reflection method.GetValue(). You can try to parse it to DateTime or any other type that you check.

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