Question on C # interface

If I need a bunch of classes to implement the method, I can just get them to implement the interface. However, if I want the method to always be decorated with two custom attributes, if there is syntax for this? In other words, I want each class that implements the Run () method to add a descriptionAttribute attribute and a versionAttribute attribute.

Update: is there a way to make classes that implement Run () generate a compilation error if they don't attach two attributes?

+7
c #
source share
5 answers
public interface IRun { void Run(); } public abstract class RunBase : IRun { [Description("Run Run Run")] [Version("1.0")] public abstract void Run(); } public abstract class SoRunning : RunBase { public override void Run() {} } 

you must remove the attributes from the base class

+6
source share

There is no compilation method to ensure its execution.

+3
source share

Perhaps you should consider using abstract classes? http://msdn.microsoft.com/en-us/library/k535acbf%28VS.71%29.aspx

(Not sure I understood your question well)

+3
source share

I do not think that native compile time support. However, one way you can get around this is to create a program or script that runs at compile time using project creation events.

For example:

  • Create a small program that takes the path to the assembly through the command line.
  • Make the program load the assembly from the command line
  • Get all types from assembly
  • Make sure all types that implement your interface have set attributes.
  • Ask the program to throw an exception if the conditions are not met, otherwise it will be successfully executed.
  • Add program to event commands after assembly via project properties

Note. It can also be performed as a β€œsingle” test.

+1
source share

You can use an abstract class to check attributes when initializing a class.

 abstract class MustImpliment { protected MustImpliment() { object[] attributes = this.GetType().GetCustomAttributes(typeof(DescriptionAttribute), true); if (attributes == null || attributes.Length == 0) throw new NotImplementedException("Pick a better exception"); } // Must impliment DescriptionAttribute public abstract void DoSomething(); } class DidntImpliment : MustImpliment { public override void DoSomething() { // ... } } 

Update: this will not cause a compiler error, but you can use it as part of the Unit Test, as suggested by Jerod Hewtelling.

0
source share

All Articles