Interface 接口的DisplayName属性

Interface 接口的DisplayName属性,interface,attributes,Interface,Attributes,是否有其他方法更改界面的显示名称? 编译器告诉DisplayName属性仅对类有效 [DisplayName("Employee")] <- issue with this interface IPerson { ... ... } [DisplayName(“Employee”)]任何属性都不能应用于接口。以下是有效属性目标的列表 您可以创建一个所有成员都是抽象的抽象类。在某种程度上,这与具有属性的接口相同。但是使用抽象类代替接口还有其他影响应用程序体系结构的影响。问题

是否有其他方法更改界面的显示名称? 编译器告诉DisplayName属性仅对类有效

[DisplayName("Employee")]  <- issue with this
interface IPerson
{   ...
    ...
}

[DisplayName(“Employee”)]任何属性都不能应用于接口。以下是有效属性目标的列表


您可以创建一个所有成员都是抽象的抽象类。在某种程度上,这与具有属性的接口相同。但是使用抽象类代替接口还有其他影响应用程序体系结构的影响。

问题是
DisplayNameAttribute
具有
class | Method | Property | Event
AttributeTargets
,因此禁用对接口的使用。
可能没有特别的设计原因,只是从来没有需要过,所以从来没有考虑过

最简单的解决方案是扩展属性并应用您自己的
AttributeTargets

[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event)]
公共类MyDisplayNameAttribute:System.ComponentModel.DisplayNameAttribute
{
公共MyDisplayNameAttribute(字符串名称):基(名称){}
}
[MyDisplayName(“新名称”)]
接口IMyInterface{}
这种方法的良好效果是,您可以像“普通”的DisplayNameAttribute一样检索它:

var attrs=typeof(IMyInterface).GetCustomAttributes(typeof(System.ComponentModel.DisplayNameAttribute),false);

这是不正确的,我不确定为什么该文档如此不正确(即使大写也是错误的),但是
接口
(1024)自.NET Framework 1.1以来一直在
属性获取
枚举中-这很好:
[过时]接口IWithAttribute{}
var attrs=typeof(IWithAttribute).GetCustomAttributes(false)
Console.WriteLine(attrs[0].GetType().Name);//给出:废弃属性