簡體   English   中英

如何確定一個屬性是否是帶有反射的自動實現的屬性?

[英]How to find out if a property is an auto-implemented property with reflection?

所以就我而言,我正在使用反射來發現類的結構。 我需要能夠確定某個屬性是否是 PropertyInfo 對象自動實現的屬性。 我假設反射 API 不會公開此類功能,因為自動屬性依賴於 C#,但是否有任何解決方法來獲取此信息?

您可以檢查getset方法是否標有CompilerGenerated屬性。 然后,您可以將其與查找標記為CompilerGenerated屬性的私有字段相結合,該屬性包含屬性名稱和字符串"BackingField"

也許:

public static bool MightBeCouldBeMaybeAutoGeneratedInstanceProperty(
    this PropertyInfo info
) {
    bool mightBe = info.GetGetMethod()
                       .GetCustomAttributes(
                           typeof(CompilerGeneratedAttribute),
                           true
                       )
                       .Any();
    if (!mightBe) {
        return false;
    }


    bool maybe = info.DeclaringType
                     .GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
                     .Where(f => f.Name.Contains(info.Name))
                     .Where(f => f.Name.Contains("BackingField"))
                     .Where(
                         f => f.GetCustomAttributes(
                             typeof(CompilerGeneratedAttribute),
                             true
                         ).Any()
                     )
                     .Any();

        return maybe;
    }

它不是萬無一失的,非常脆弱,可能無法移植到 Mono 等。

這應該做:

public static bool IsAutoProperty(this PropertyInfo prop)
{
    return prop.DeclaringType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
                             .Any(f => f.Name.Contains("<" + prop.Name + ">"));
}

原因是對於自動屬性,支持FieldInfoName屬性如下所示:

<PropertName>k__BackingField

由於字符<>不會出現在普通字段中,具有這種命名的字段指向自動屬性的支持字段。 正如傑森所說,它仍然很脆弱。

或者讓它快一點,

public static bool IsAutoProperty(this PropertyInfo prop)
{
    if (!prop.CanWrite || !prop.CanRead)
        return false;

    return prop.DeclaringType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
                             .Any(f => f.Name.Contains("<" + prop.Name + ">"));
}

暫無
暫無

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

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