从SafeHandle继承时,我们应该重新应用ReliabilityContract属性吗?

时间:2010-06-19 21:37:30

标签: c# pinvoke

在SafeHandles上的.Net security blog article中,它提到您需要将ReliabilityContract属性应用于关闭句柄的本机方法的签名。

当我们从SafeHandle继承时,我们必须声明一个构造函数,ReleaseHandle方法和IsInvalid属性,所有这些都在基类中应用了ReliabilityContract(我使用Reflector来查看SafeHandle):

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected SafeHandle(IntPtr invalidHandleValue, bool ownsHandle);

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected abstract bool ReleaseHandle();

public abstract bool IsInvalid { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get; }

ReliabilityContract有its inherited property set to false - 我认为这意味着我们覆盖的方法将不再具有属性 - 那么,我们是否需要重新应用属性?

1 个答案:

答案 0 :(得分:2)

是的,您必须重新应用该属性,因为ReliabilityContract的继承属性设置为false,这意味着派生类中的方法不会应用该属性。

看看下面的代码。如果将Inherited命名参数设置为false,则派生类中的Method1不会应用该属性。之后,将相同的参数(继承)设置为true并再次运行。

[AttributeUsage(AttributeTargets.Method, Inherited=false)]
public class MyAttribute : Attribute { }

class BaseClass
{
    [My] // MyAttribute applied to base class
    public virtual void Method1() { }
}

class DerivatedClass : BaseClass
{
    // MyAttribute not applied to derivate class
    public override void Method1() { }
}

public class Program
{
    static void Main(string[] args)
    {
        var attributes = typeof(DerivatedClass)
            .GetMethod("Method1")
            .GetCustomAttributes(true);

        foreach (var attr in attributes)
        {
            Console.Write(attr.ToString());
        }
    }
} 
相关问题