【发布时间】:2012-02-03 14:12:46
【问题描述】:
我有一个简单的课程。而且我必须为一些方法和属性添加一些条件。例如:
public class Example
{
public Boolean Condition {get; set;}
public Double ConditionValue {get; set;}
[Verify("!Condition && ConditionValue>5")]
public void DoSomthing()
{ ... }
}
我想检查一个方面属性中的条件(例如,“!Condition && ConditionValue>5”)。我无法将动作/功能赋予属性,因此我给出了一个简单的字符串。我需要把这个字符串翻译成一个条件:
[Serializable]
public class MyAspectAttribute : OnMethodBoundaryAspect
{
public override void OnExit(MethodExecutionArgs args)
{
if (!this.Condition && this.ConditionValue>5) // If-statment from string, this is the problem...
{ ... }
}
}
如何从字符串中提取真正的 if 语句?我看到了一些解决方案,但我不确定它们是否正常:
- 使用运行时编译器,例如CSharpCodeProvider。
- 使用诸如http://flee.codeplex.com/之类的库
- 还有什么...?
我怎样才能优雅地做到这一点?谢谢!
更新:我已经编辑了关于建议的问题... Upd2:我不尝试验证我的代码,我可以这样做:
public class Example2
{
public Boolean Condition {get; set;}
[LoggingIf("Condition")]
public void DoSomthing1()
{ ... }
[PrintReportIf("!Condition")]
public void DoSomthing2()
{ ... }
}
【问题讨论】:
-
为什么在这种情况下自定义属性?
-
我尝试为班级成员添加一些逻辑。这是可行的,但我正在寻找一个很好的解决方案......以及如何在没有属性的情况下为很多(!)属性和方法添加一些逻辑......?
-
在属性中包含代码后,您期望什么会调用您的代码?属性对它们装饰的成员一无所知,也没有任何“调用”属性。他们只指定元数据。
-
Postsharp 可以以不同方式使用此元数据... =) 一种方法 - 将此字符串作为 if-statement(?) 插入方法主体...
-
@DragonFire - 如果您使用 PostSharp,那么有什么问题?
标签: c# if-statement compilation conditional postsharp