CallerMemberName 不适用于字段上的属性构造函数

本文关键字:属性 构造函数 字段 不适用 适用于 CallerMemberName | 更新日期: 2023-09-27 18:35:24

我正在用 C# (.NET 4.5、VS 2013) 生成序列化程序,并且我正在使用属性来控制序列化元数据,例如用于存储成员以进行读取和写入的名称。由于我不想每次都写出成员名称作为属性的参数,因此我尝试使用 CallerMemberName。

对于属性,

它工作正常:属性名称在调用构造函数时传递,属性允许我在反序列化中分配属性值。

对于字段,无论出于何种原因,CallerMemberName 都拒绝工作。相反,我得到了默认字符串。每次都为空,即使其他参数参数正确传递也是如此。

我目前用于测试的代码是:

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);
    }
}

我已经在字段未收到参数的情况下对其进行了测试,字段接收参数以确保正在调用构造函数,字段抛出构造函数异常以加倍确保构造函数被调用,我无法弄清楚我做错了什么。

CallerMemberName 不适用于字段上的属性构造函数

正如 MSDN 所述,引用:

允许您获取调用方的方法或属性名称 方法。

所以你必须找到另一种方法来做你正在做的事情,或者坚持使用属性。