【发布时间】: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