我为线程同步创建了一个类,我希望将其应用于方法,类,属性等,而无需通过并将我的代码插入到每个函数,类等中。这是我必须执行的当前实现的示例:
public class NotWhatIWantExample
{
LockingClass locker;
public int function()
{
locker.EnterWriteBlock();
if (condition)
{
locker.LeaveWriteBlock();
return 0;
}
locker.LeaveWriteBlock();
return 1;
}
}
接下来是我想要做的两个例子
示例2:
// [LockingClassAttribute(LockingClassAttribute.WriteBlock)]
// Not Declared But Added Since Attribute Is Applied On A Method
public class WhatIWantExample
{
//LockingClass locker; Included In The Attribute
[LockingClassAttribute(LockingClassAttribute.WriteBlock)]public int function()
{
if (condition)
return 0;
}
}
示例3:
[LockingClassAttribute(LockingClassAttribute.ReadWriteBlock)]
public class WhatIWantExample
{
//LockingClass locker; Included In The Attribute
//Function Would Override LockingClassAttribute.ReadWriteBlock
[LockingClassAttribute(LockingClassAttribute.WriteBlock)]public int function()
{
if (condition)
return 0;
return 1;
}
//Would Inherit [LockingClassAttribute(LockingClassAttribute.ReadWriteBlock)]
public int function2()
{
if (condition)
return 0;
return 1;
}
}
这可能吗?
答案 0 :(得分:2)
这是aspect orientated programming的一个例子。它不能直接在C#中使用,但您可以使用PostSharp来执行此类操作。
查看OnMethodBoundaryAspect类,它允许您在方法运行之前和完成之后运行代码。
答案 1 :(得分:1)
你所追求的是aspect oriented programming
。我自己从未应用过,但有一些现成的解决方案。参见例如:Aspect Oriented Programming in C#