[英]C# Custom Attributes not being applied
我正在嘗試使用MetadataType屬性類將屬性應用於字段。 我無法將自定義屬性應用於部分類中的字段。 我一直關注的一些示例在這里和這里 。
我的最終結果是嘗試標記我需要“進行一些工作”的類中的所有字段。
在下面的示例中,我希望字段“名稱”具有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字段非常有用-但我希望這樣做是因為它在分部類中。 名稱字段不會從元數據中提取屬性,而這正是我真正需要的。
我缺少什么,還是我弄錯了?
更新:這就是我搜索具有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);
}
}
}
結果是:
重量
但我期望:
名稱
重量
屬性是元數據的一部分,它們不影響編譯結果。 將MetadataType
屬性設置為該類不會將所有元數據傳播到該類的屬性/字段。 因此,您必須閱讀代碼中的MetadataType
屬性,並使用MetadataType
屬性中定義的類型的MetadataType
代替初始類(或一起使用)
檢查樣本:
var fooFields = new Dictionary<FieldInfo, FooAttribute>();
var cowType = typeof (Cow);
var metadataType = cowType.GetCustomAttribute<MetadataTypeAttribute>();
var metaFields = metadataType?.MetadataClassType.GetFields() ?? new FieldInfo[0];
foreach (var fieldInfo in cowType.GetFields())
{
var metaField = metaFields.FirstOrDefault(f => f.Name == fieldInfo.Name);
var foo = metaField?.GetCustomAttribute<FooAttribute>()
?? fieldInfo.GetCustomAttribute<FooAttribute>();
if (foo != null)
{
fooFields[fieldInfo] = foo;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.