【问题标题】:Can I add code to a method via an Attribute?我可以通过属性向方法添加代码吗?
【发布时间】:2017-01-18 19:42:42
【问题描述】:

如果方法具有特定属性,我希望能够在方法的开头添加一些代码。例如,如果它具有特定属性并且是星期三,我希望它立即返回:

[Return()]
public void MyMethod()
{
    //If [Return()] attribute and its Wednesday, it returns and never "Does Stuff"
    //Do Stuff
}

我的属性已经开始,但我不知道如何在方法之前运行代码。

[AttributeUsage(AttributeTargets.Method)]
public class ReturnAttribute : Attribute
{
     public void Return()
     {
         if(Today == Wednesday)
         {
             return;
         }
     {   
}

我知道ReturnAttribute 不正确。我发布了该代码以显示我离我有多近(或多远)。

如果方法标有指定的属性,我如何在方法的开头插入代码?

【问题讨论】:

  • 你可能想看看 Fody 库,看看它们是如何工作的
  • 您必须向每个添加了[Return] 的方法添加代码,以使用反射来查找属性、实例化它然后运行它。将返回 bool 的单行辅助方法添加到方法的顶部并在其为真时返回会简单得多。 ``` public void Blah() { if (Helper.IsItWednesday()) { return; } } ```
  • 这个技术都是关于方法拦截的。请看一下这个问题:stackoverflow.com/questions/25366243/intercept-method-calls。仔细看看第二个答案,想象一下_stopWatch = Stopwatch.StartNew(); 被“if day not is Wednesday”替换

标签: c# annotations attributes


【解决方案1】:

编译时解决方案

也许您可以尝试使用ConditionalAttribute,并设置一个永远不成立的条件。比如……

[Conditional("NEVER")]
public static void MyMethod(int x)
{
    //This code will never run
}

这将具有您想要的效果,但仅限于编译时。请注意,这仅适用于返回 void 的方法。不确定要对返回其他内容的方法做什么,因为您不希望运行任何代码,因此无法实例化任何要返回的对象。

运行时,可剪切和粘贴解决方案

在方法的顶部添加一点反射:

using System.Reflection;
using System.Linq;

[Return()]
void MyMethod(int x)
{
    var skip = MethodBase.GetCurrentMethod().GetCustomAttributes( typeof( ReturnAttribute ), false ).Any();
    if (skip) return;
    //Rest of the code goes here
}

【讨论】:

  • 谢谢,但我不明白这是如何工作的(即使在阅读了链接的文档之后)。我更新了我的问题以使其更清楚,因为我认为您的回答只说明了一个方法是否可以编译。
  • 添加了第二个运行时检查选项。
猜你喜欢
  • 2010-11-25
  • 2015-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
相关资源
最近更新 更多