为什么我的 .NET 属性不执行操作? [英] Why does my .NET Attribute not perform an action?

查看:24
本文介绍了为什么我的 .NET 属性不执行操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的属性:

I've created a simple Attribute:

[AttributeUsage(AttributeTargets.Method)]
public class InitAttribute : System.Attribute
{
    public InitAttribute()
    {
        Console.WriteLine("Works!");
    }
}

我将其应用于一个简单的方法:

and I apply it to a simple method:

static class Logger
{
    public static string _severity;

    public static void Init(string severity)
    {
        _severity = severity;
    }

    [Init()]
    public static void p()
    {
        Console.WriteLine(_severity);
    }
}

正在发生的事情非常直接.只是,我希望该属性执行一个操作(打印 Works!),但这不会发生.

What is going on is pretty streight-forward. Only, I expect the attribute to perform an action (printing Works!), but this does not happen.

另外,打印Works!"当然只是出于调试目的:我想访问 instance 的属性 _severity(例如,检查是否为 != null),但我所做的一切继续阅读属性(对我来说很新)是关于通过反射访问的方法或属性等等.一旦我评估了 _severity,我该如何修改被装饰方法的行为(在这种情况下,引发异常记录器未初始化"并且不执行它)?

Addictionally, printing "Works!" is of course just for debugging purposes: I'd like to access the instance's property _severity (to check if is != null, for example), but everything I keep reading about attributes (that are pretty new to me) is about accessing the class' methods or properties and so on via reflection. Once I've evaluated _severity, how can I modify the behavior of the decorated method (in this case, rise an exception "Logger is not initialized" and do not execute it)?

任何帮助表示赞赏.

推荐答案

如果您需要在控件进入方法时执行操作,您应该查看 面向方面的编程和框架,例如 PostSharp.属性并非旨在自行执行任何操作.它们只是附加在 IL 程序集中的东西上的一堆数据(或元数据,如果你愿意的话),可以在运行时查询.

If you need to perform an action as control enters a method, you should look at aspect-oriented programming and frameworks such as PostSharp. Attributes are not designed to perform anything by themselves. They are just a bunch of data (or metadata if you will) attached to stuff in IL assemblies that can be queried at runtime.

这篇关于为什么我的 .NET 属性不执行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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