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

自动调用属性的构造函数-C#,c#,attributes,C#,Attributes,调用CodedMethod()时,是否有方法自动调用CallCommonCode()属性构造函数 using System; [AttributeUsage(AttributeTargets.Method|AttributeTargets.Struct, AllowMultiple=false,Inherited=false)] public class CallCommonCode : Attribute { public CallCommonC

调用
CodedMethod()
时,是否有方法自动调用
CallCommonCode()
属性构造函数

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();
  }
}

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

属性的意义只是用额外的元数据标记东西,但严格来说,它实际上不是代码本身的一部分

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

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();
    }
}
类程序
{
[过时]
公共函数()
{
}
公共静态void Main()
{
//要读取属性,只需要类型元数据,
//我们可以从两种方式中选择一种。
Type typedata1=typeof(Program);//这是在编译时确定的。
Type typedata2=new Program().GetType();//这是在运行时确定的
//现在我们只需扫描属性(这将获取类“Program”上的属性)
IEnumerable attributesOnProgram=typedata1.GetCustomAttributes();
//要获取方法的属性,我们需要(这会获取函数“SomeFunction”的属性)
IEnumerable methodAttributes=typedata1.GetMethod(“SomeFunction”).GetCustomAttributes();
}
}

那么我们如何避免这种情况呢?那么[Dllimport]和[Observe]属性是如何工作的呢?Visual Studio会监视这些属性。从技术上讲,属性不是代码的一部分,必须有人在某处监视它们。我会写一个例子。回答得好。Ô.o为什么要做这样的事情?@Aniket听起来像是想采用面向方面的编程。幸运的是,您可以使用PostSharp这样的工具来实现这一点:@DHN好吧,我正在努力提高我的C#技能,尽可能多地学习。我可能还想做一些类似MVC的事情WebForms@Aniket好吧,我以为你想试试很奇怪的东西;o) 嗯,
sircodesalot
是对的:o)