2017-03-24 75 views
0

我们可以设置自定义以下列方式中引用的DLL的属性类型:设置在枚举值自定义属性中引用的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

*我们可以设置类型的自定义属性*你确定吗? – xanatos

+0

@xanatos是的,我敢肯定... –

+0

通过引用您的意思是其他第三方DLL? –

回答

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子系统,但它是专门用于设计师。