0

有没有办法在调用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();
  }
}
4

1 回答 1

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();
    }
}
于 2013-02-07T15:54:10.460 回答