【发布时间】:2017-11-22 00:51:55
【问题描述】:
我正在尝试使用 MetadataType 属性类将属性应用于字段。我无法将自定义属性应用于部分类中的字段。我一直关注的一些例子是here 和here。
我的最终目标是尝试标记一个类中我需要“做一些工作”的所有字段。
在下面的示例中,我希望“名称”字段应用 FooAttribute。在现实生活中,我正在处理生成的代码......
在我非常做作的例子中,我有一个部分类 - Cow,它是生成的代码;
namespace Models
{
public partial class Cow
{
public string Name;
public string Colour;
}
}
我需要 Name 字段来使用我的 FooAttribute,所以我这样做了;
using System;
using System.ComponentModel.DataAnnotations;
namespace Models
{
public class FooAttribute : Attribute { }
public class CowMetaData
{
[Foo]
public string Name;
}
[MetadataType(typeof(CowMetaData))]
public partial class Cow
{
[Foo]
public int Weight;
public string NoAttributeHere;
}
}
这对于应用了 FooAttribute 的 Weight 字段非常有用 - 但我希望这是因为它在部分类中。 Name 字段不会从元数据中获取属性,而这正是我真正需要的。
我遗漏了什么,还是我完全搞错了?
更新:这就是我使用 FooAttribute 搜索字段的方式;
public static void ShowAllFieldsWithFooAttribute(Cow cow)
{
var myFields = cow.GetType().GetFields().ToList();
foreach (var f in myFields)
{
if (Attribute.IsDefined(f, typeof(FooAttribute)))
{
Console.WriteLine("{0}", f.Name);
}
}
}
这样的结果是:
重量
但我期待:
名称
重量
【问题讨论】:
标签: c# custom-attributes metadatatype