簡體   English   中英

確定是否可以為反射屬性分配給定值

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

確定反射屬性是否可以分配給定值的最簡單方法是什么?

我需要的方法簽名是:

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

此方法適用於值類型和引用類型,並且值是否為null。

謝謝您的幫助。

Manitra。

您可能正在尋找Type.IsAssignableFrom

您無法確定作為object傳遞的null的類型。 您只能說該屬性是否完全可以為null

出於這個原因,您可以采用編譯時類型:

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

感謝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;
}

這適用於所有情況,並且以純粹的松散鍵入方式起作用。

Manitra。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM