【问题标题】:CallerMemberName doesn't work for Attribute constructor on a fieldCallerMemberName 不适用于字段上的属性构造函数
【发布时间】:2016-05-31 01:01:42
【问题描述】:

我正在用 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);
    }
}

我已经测试了它的字段不接收参数,字段接收参数以确保构造函数被调用,字段抛出构造函数异常以双重确保构造函数被调用,我可以不知道我做错了什么。

【问题讨论】:

  • Docs.ms 需要文档修复。 “调用者信息”文章指出,如果“调用发生在 [an] 属性构造函数 [然后] 成员名称结果 [是] 应用该属性的成员的名称”。似乎让它保持打开状态,它可能适用于字段,但我也可以确认它不起作用。

标签: c# custom-attributes callermembername


【解决方案1】:

正如MSDN 所说,引用:

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

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

【讨论】:

  • 有道理,因为从语义上讲,一个字段不能调用任何东西 - CallerMemberName 中的 Caller 不适用于它。
  • 然而,对构造函数的调用在字段或属性中都不是显式的 - 并且正在调用属性构造函数。我想真正的谜团是在该领域的情况下如何称呼它。在微软病态的语法糖堆上再扔一件事。
猜你喜欢
  • 1970-01-01
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-02
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
相关资源
最近更新 更多