简体   繁体   English

C# 通过反射获取属性值没有默认值

[英]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.如您所见,通过反射获取值并与默认值进行比较返回 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.有人指出,GetValue() 的返回值是 object,因此必须将其转换为 DateTime 才能使默认值起作用。 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).不幸的是,我不能,因为我正在对 object 的所有属性运行此测试,以发现此 object 是否已初始化(因此我检查 null 或默认值)。 And the messageDto in reality is a generic type so I don't know the types of its properties a priori.而 messageDto 实际上是一个泛型类型,所以我不知道它的属性类型是先验的。

GetValue returns an object of type object , because it can't know at compile time what the type of the property is. GetValue返回 object 类型的object ,因为它在编译时无法知道属性的类型。 The default value of an object is null , but since DateTime is a value type, its default value cannot be null . nulldefault值为object ,但由于 DateTime 是值类型,其default值不能为null

Cast the result of GetValue to DateTime .GetValue的结果转换为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.我通过将其转换为字符串来检查随机 object 值,并尝试解析为我检查的类型。 Value parameter is returned by reflection method.GetValue().值参数由反射方法返回。GetValue()。 You can try to parse it to DateTime or any other type that you check.您可以尝试将其解析为 DateTime 或您检查的任何其他类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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