亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 743 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號