在调用方法之前处理信息的自定义属性 [英] Custom Attribute to Process info before a method is called

查看:77
本文介绍了在调用方法之前处理信息的自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个属性,以在调用方法之前处理一些信息,但该方法没有被调用.

I have create a attribute to process some info before a method is called but it is not getting called.

由于要调用类的其他方法,我想记录一些处理后的值,这些值存储在类的静态字段中.

I want to log some values which are process and stored in a static field in the class, as a result of other methods of my class called.

有人可以对此进行指导.

So can someone guide on it.

[AttributeUsage(AttributeTargets.Method)]
internal class MyAttrib : Attribute
{
    public MyAttrib()
    {
        //This is not getting called. what am i missing
        Console.WriteLine("My Attrib called!!");
    }
}

class MyClass
{
    public MyClass()
    {
        Console.WriteLine("Constructor Created");
    }

    [MyAttrib]
    public int Opt1()
    {
        Console.WriteLine("Op1 Performed");
        return 0;
    }

}

static void Main(string[] args)
{
        MyClass cla = new MyClass();
        cla.Opt1();
        cla.Opt2();
        Console.ReadLine();
}

推荐答案

属性通常不在运行时实例化.您可以使用反射来获得将哪些属性应用于代码的各个部分(类型,字段等)以及这些属性的内容.

Attributes are not usually instantiated during run-time. You use reflection to obtain what attributes are applied to various parts of the code (types, fields, etc) and what the contents of the attributes are.

在访问MSDN上的此页面上.具体来说,该部分指出:

Read this page on MSDN regarding accessing attributes. Specifically, the part that states:

属性规范,例如:

[Author("P. Ackerman", version = 1.1)]
class SampleClass

在概念上等同于此:

Author anonymousAuthorObject = new Author("P. Ackerman");
anonymousAuthorObject.version = 1.1;

但是,直到查询SampleClass的属性后,代码才执行.在SampleClass上调用GetCustomAttributes会导致Author对象如上所述被构造和初始化.

您可能能够做的一件事就是拥有一个基类,您创建的所有其他类都源自该基类.在该基类的构造函数中,使用反射来标识您感兴趣的类的任何属性或其他任何内容,并对这些信息进行处理.

One thing you might be able to do is have a base class from which all other classes you create derive from. In this base class's constructor, use reflection to identify any attributes or anything else about the class that you're interested in and do something with that information.

这实际上并没有解决您关于在执行方法之前处理某些信息的声明,尽管...我认为这是不可能的.

This doesn't actually address your statement about processing some info before a method is executed, though... I don't believe that is possible.

这篇关于在调用方法之前处理信息的自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆