为了账号安全,请及时绑定邮箱和手机立即绑定

C#类可以从其接口继承属性吗?

C#类可以从其接口继承属性吗?

C#
慕无忌1623718 2019-11-13 14:33:53
这似乎暗示“否”。不幸的是。[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class, AllowMultiple = true, Inherited = true)]public class CustomDescriptionAttribute : Attribute{    public string Description { get; private set; }    public CustomDescriptionAttribute(string description)    {        Description = description;    }}[CustomDescription("IProjectController")]public interface IProjectController{    void Create(string projectName);}internal class ProjectController : IProjectController{    public void Create(string projectName)    {    }}[TestFixture]public class CustomDescriptionAttributeTests{    [Test]    public void ProjectController_ShouldHaveCustomDescriptionAttribute()    {        Type type = typeof(ProjectController);        object[] attributes = type.GetCustomAttributes(            typeof(CustomDescriptionAttribute),            true);        // NUnit.Framework.AssertionException:   Expected: 1   But was:  0        Assert.AreEqual(1, attributes.Length);    }}类可以从接口继承属性吗?还是我在这里树错树了?
查看完整描述

3 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

否。每当实现接口或重写派生类中的成员时,都需要重新声明属性。


如果您只关心ComponentModel(而不是直接反射),则有一种方法([AttributeProvider])从现有类型中建议属性(以避免重复),但这仅对属性和索引器用法有效。


举个例子:


using System;

using System.ComponentModel;

class Foo {

    [AttributeProvider(typeof(IListSource))]

    public object Bar { get; set; }


    static void Main() {

        var bar = TypeDescriptor.GetProperties(typeof(Foo))["Bar"];

        foreach (Attribute attrib in bar.Attributes) {

            Console.WriteLine(attrib);

        }

    }

}

输出:


System.SerializableAttribute

System.ComponentModel.AttributeProviderAttribute

System.ComponentModel.EditorAttribute

System.Runtime.InteropServices.ComVisibleAttribute

System.Runtime.InteropServices.ClassInterfaceAttribute

System.ComponentModel.TypeConverterAttribute

System.ComponentModel.MergablePropertyAttribute


查看完整回答
反对 回复 2019-11-13
  • 3 回答
  • 0 关注
  • 665 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信