Сергей Asked:2020-03-27 03:40:34 +0000 UTC2020-03-27 03:40:34 +0000 UTC 2020-03-27 03:40:34 +0000 UTC 属性接口 772 是否可以将属性与接口一起使用,以便实现类具有具有相同属性的方法? c# 2 个回答 Voted Best Answer Андрей NOP 2020-03-27T13:17:30Z2020-03-27T13:17:30Z 不,接口属性不会被它们的实现类继承。 如果要继承属性,则必须使用抽象类而不是接口。同时,需要显式表明该属性是继承的(属性Inherited中AttributeUsage的一个属性),并且在获取它时,需要显式表明我们对继承的属性感兴趣(inherit方法族中的一个参数GetCustomAttribute[s]): class Program { static void Main(string[] args) { Console.WriteLine( typeof(C1) .GetMethod(nameof(C1.Method)) .GetCustomAttribute<InheritanceAttribute>( // <== using System.Reflection; inherit: false) is InheritanceAttribute ); // False Console.WriteLine( typeof(C1) .GetMethod(nameof(C1.Method)) .GetCustomAttribute<InheritanceAttribute>( inherit: true) is InheritanceAttribute ); // True Console.WriteLine( typeof(C2) .GetMethod(nameof(C2.Method)) .GetCustomAttribute<NonInheritanceAttribute>( inherit: false) is NonInheritanceAttribute ); // False Console.WriteLine( typeof(C2) .GetMethod(nameof(C2.Method)) .GetCustomAttribute<NonInheritanceAttribute>( inherit: true) is NonInheritanceAttribute ); // False Console.ReadKey(); } } [AttributeUsage(AttributeTargets.All, Inherited = true)] class InheritanceAttribute : Attribute { } [AttributeUsage(AttributeTargets.All, Inherited = false)] class NonInheritanceAttribute : Attribute { } abstract class AC1 { [Inheritance] public abstract void Method(); } abstract class AC2 { [NonInheritance] public abstract void Method(); } class C1 : AC1 { public override void Method() { } } class C2 : AC2 { public override void Method() { } } 以下是语言开发人员关于从接口继承属性的解释:论坛:接口中的代码优先数据注释 Qwertiy 2020-03-27T04:41:30Z2020-03-27T04:41:30Z 是的,您可以:https ://ideone.com/gObRwA using System; class SomeAttribute : Attribute {} [Some()] interface I { void Method(); } public class Test : I { [Some()] public void Method() {} public static void Main(){} }
不,接口属性不会被它们的实现类继承。
如果要继承属性,则必须使用抽象类而不是接口。同时,需要显式表明该属性是继承的(属性
Inherited中AttributeUsage的一个属性),并且在获取它时,需要显式表明我们对继承的属性感兴趣(inherit方法族中的一个参数GetCustomAttribute[s]):以下是语言开发人员关于从接口继承属性的解释:论坛:接口中的代码优先数据注释
是的,您可以:https ://ideone.com/gObRwA