我创建了一个用于线程同步的类,我想将其应用于方法,类,属性等,而无需遍历并将代码插入每个函数,类等中。这是当前必须执行的示例:
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;
}
}
这可能吗?
最佳答案
这是aspect orientated programming的示例。它在C#中不是直接可用的,但是您可以使用PostSharp来进行此类操作。
看一下OnMethodBoundaryAspect类,该类使您可以在方法运行之前和完成之后运行代码。
关于c# - 包装功能的属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21279702/