自动调用属性的构造函数 - C#

时间:2013-02-07 15:47:47

标签: c# attributes

调用CallCommonCode()时,有没有办法自动调用CodedMethod()属性构造函数?

using System;

[AttributeUsage(AttributeTargets.Method|AttributeTargets.Struct,
                   AllowMultiple=false,Inherited=false)]
public class CallCommonCode : Attribute
{
    public CallCommonCode() { Console.WriteLine("Common code is not called!"); }
}

public class ConcreteClass {

  [CallCommonCode]
  protected void CodedMethod(){
     Console.WriteLine("Hey, this stuff does not work :-(");
  }
  public static void Main(string[] args)
  {
     new ConcreteClass().CodedMethod();
  }
}

1 个答案:

答案 0 :(得分:2)

不,因为该属性独立于函数而存在。您可以扫描属性,也可以执行该功能,但不能同时执行这两项操作。

属性的重点只是标记具有额外元数据的内容,但严格来说并不是代码本身的一部分。

在这种情况下,您通常会扫描函数上的标记,如果它违反您的业务逻辑,您会抛出某种异常。但一般来说,属性只是一个“标记”。

class Program
{
    [Obsolete]
    public void SomeFunction()
    {

    }

    public static void Main()
    {
        // To read an attribute, you just need the type metadata, 
        // which we can get one of two ways.
        Type typedata1 = typeof(Program);       // This is determined at compile time.
        Type typedata2 = new Program().GetType(); // This is determined at runtime


        // Now we just scan for attributes (this gets attributes on the class 'Program')
        IEnumerable<Attribute> attributesOnProgram = typedata1.GetCustomAttributes();

        // To get attributes on a method we do (This gets attributes on the function 'SomeFunction')
        IEnumerable<Attribute> methodAttributes = typedata1.GetMethod("SomeFunction").GetCustomAttributes();
    }
}