简体   繁体   English

确定是否可以为反射属性分配给定值

[英]Determine if a reflected property can be assigned a given value

What is the easiest way to determine if a reflected property can be assigned a given value ? 确定反射属性是否可以分配给定值的最简单方法是什么?

The method signature of what I need is : 我需要的方法签名是:

public static bool IsAssignable(PropertyInfo property, object value)
{        
    throw new NotImplementedException();
}

This method should work for value type and reference type and weither value is null or not. 此方法适用于值类型和引用类型,并且值是否为null。

Thanks for you help guys. 谢谢您的帮助。

Manitra. Manitra。

您可能正在寻找Type.IsAssignableFrom

You can't determine the type of null which is passed as object . 您无法确定作为object传递的null的类型。 You only can say if the property is able to take null at all. 您只能说该属性是否完全可以为null

You could take the compile-time type for that reason: 出于这个原因,您可以采用编译时类型:

public static bool IsAssignable<T>(PropertyInfo property, T value)
{        
    if (value != null)
    {
        return property.PropertyType.IsAssignableFrom(value.GetType());
    }
    return property.PropertyType.IsAssignableFrom(typeof(T));
}

Thanks to Stefan's and John responses, and the "Determine if a reflected property can be assigned null" question, here is the code I'll use : 感谢Stefan和John的回答,以及“确定是否可以将一个反射的属性分配为空”问题,这是我将使用的代码:

public static bool IsAssignable(PropertyInfo property, object value)
{
    if (value == null && property.PropertyType.IsValueType && Nullable.GetUnderlyingType(property.PropertyType) == null)
        return false;
    if (value != null && !property.PropertyType.IsAssignableFrom(value.GetType()))
        return false;
    return true;
}

This works for all cases and in a pure loosely typed fashion. 这适用于所有情况,并且以纯粹的松散键入方式起作用。

Manitra. Manitra。

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

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