猿问

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

这似乎暗示“否”。不幸的是。


[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);

    }

}

类可以从接口继承属性吗?还是我在这里树错树了?


慕无忌1623718
浏览 699回答 3
3回答

慕丝7291255

否。每当实现接口或重写派生类中的成员时,都需要重新声明属性。如果您只关心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.SerializableAttributeSystem.ComponentModel.AttributeProviderAttributeSystem.ComponentModel.EditorAttributeSystem.Runtime.InteropServices.ComVisibleAttributeSystem.Runtime.InteropServices.ClassInterfaceAttributeSystem.ComponentModel.TypeConverterAttributeSystem.ComponentModel.MergablePropertyAttribute
随时随地看视频慕课网APP
我要回答