编程语言
首页 > 编程语言> > c#-包装函数的属性?

c#-包装函数的属性?

作者:互联网

我创建了一个用于线程同步的类,我想将其应用于方法,类,属性等,而无需遍历并将我的代码插入每个函数,类等中.这是当前必须执行的示例:

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类,它使您可以在方法运行之前和完成之后运行代码.

标签:word-wrap,attributes,c,compilation
来源: https://codeday.me/bug/20191122/2057968.html