我们可以通过以下方式为引用的DLL中的类型设置自定义属性:
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AttributeForExternType : Attribute
{
public ExternTypeAttribute(Type type)
{
ExternType = type;
}
public Type ExternType { get; }
}
// set in assembly info:
[assembly: ExternTypeAttribute(typeof(Extern.Type))]
在项目的枚举和字段中设置自定义属性:
[AttributeUsage(AttributeTargets.Enum)]
public sealed class InternEnumAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Field)]
public sealed class InternFieldAttribute: Attribute { }
enum MyEnum
{
FieldA,
[InternFieldAttribute]
FieldB
}
问题:是否可以在引用的枚举值上定义和使用自定义属性?
答案 0 :(得分:1)
您无法将属性添加到预先存在的类型。如果可以修改源代码,则只能添加属性...
// set in assembly info:
[assembly: ExternTypeAttribute(typeof(System.Collections.Generic.List<int>))]
[assembly: ExternTypeAttribute(typeof(System.Attribute))]
[assembly: ExternTypeAttribute(typeof(System.Console))]
[assembly: ExternTypeAttribute(typeof(System.DateTime))]
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class ExternTypeAttribute : Attribute
{
public ExternTypeAttribute(Type type)
{
ExternType = type;
}
public Type ExternType { get; }
}
var attrs1 = Assembly.GetExecutingAssembly().GetCustomAttributes<ExternTypeAttribute>().ToArray();
var attrs2 = typeof(System.Collections.Generic.List<int>).GetCustomAttributes<ExternTypeAttribute>().ToArray();
var attrs3 = typeof(System.Attribute).GetCustomAttributes<ExternTypeAttribute>().ToArray();
var attrs4 = typeof(System.Console).GetCustomAttributes<ExternTypeAttribute>().ToArray();
var attrs5 = typeof(System.DateTime).GetCustomAttributes<ExternTypeAttribute>().ToArray();
Console.WriteLine("This assembly: {0}, attached to types: {1} {2} {3} {4}", attrs1.Length, attrs2.Length, attrs3.Length, attrs4.Length, attrs5.Length);
结果是:
此程序集:4,附加类型:0,0,0,0
请注意,有Type Descriptor子系统,但它是专用的,主要用于设计人员。