C# クラスはインターフェースから属性を継承できますか? 質問する

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

クラスはインターフェースから属性を継承できますか? それとも、私は間違った方向に進んでいるのでしょうか?

ベストアンサー1

いいえ。インターフェースを実装したり、派生クラスのメンバーをオーバーライドしたりするときは、必ず属性を再宣言する必要があります。

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

おすすめ記事