簡體   English   中英

CallerMemberName不適用於字段上的Attribute構造函數

[英]CallerMemberName doesn't work for Attribute constructor on a field

我正在使用C#(.NET 4.5,VS 2013)生成一個序列化程序,我正在使用一個屬性來控制序列化元數據,例如用於存儲成員的名稱以進行讀寫。 由於我不想每次都寫出成員名作為屬性的參數,我正在嘗試使用CallerMemberName。

對於屬性,它工作正常:在調用構造函數時傳遞屬性名稱,該屬性允許我在反序列化中分配屬性值。

對於字段,無論出於何種原因,CallerMemberName拒絕工作。 相反,我每次都獲得默認的string.Empty,即使其他參數參數正確傳遞也是如此。

我目前的測試代碼是:

class AttributeTest
{
    [VariableAttribute(true)]
    public string testField;

    [VariableAttribute(false)]
    public string testProperty { get; set; }

    static void Main(string[] args)
    {
        Console.WriteLine("spawning");
        AttributeTest test = new AttributeTest();
        test.testField = "sdasd";
        foreach (MemberInfo info in typeof (AttributeTest).GetMembers().Where(x => x.GetCustomAttribute(typeof(VariableAttribute)) != null))
        {

            //Console.WriteLine(info.Name);
            VariableAttribute attr = (VariableAttribute)info.GetCustomAttribute(typeof (VariableAttribute));
            Console.WriteLine(attr.testStore);
        }

        //Console.WriteLine(typeof(AttributeTest).GetMember("testField")[0].GetCustomAttributes().ElementAt(0));

        test.testProperty = "falsdka";
        Console.ReadKey();
    }
}

[AttributeUsage(AttributeTargets.Field|AttributeTargets.Property)]
public class VariableAttribute : System.Attribute
{
    public bool testStore;

    public VariableAttribute(bool test = true, [CallerMemberName] string caller = "")
    {
        testStore = test;
        Console.WriteLine(caller);
    }
}

我已經在沒有參數的字段中測試了它,字段接收一個參數以確保構造函數被調用,字段拋出一個構造函數異常,以確保構造函數被調用,我無法想象我做錯了什么。

正如MSDN所述,引用:

允許您獲取方法的調用方的方法或屬性名稱。

因此,您必須找到另一種方法來做您正在做的事情,或堅持使用屬性。

暫無
暫無

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

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