开发者

When inheriting from SafeHandle, should we reapply the ReliabilityContract attribute?

In the .Net security blog article on SafeHandles, it mentions that you need to apply the ReliabilityContract attribute to the signature of the native method that closes the handle.

When we inherit from SafeHandle we have to declare a constructor, ReleaseHandle me开发者_开发知识库thod and IsInvalid property, all of which have the ReliabilityContract applied in the base class (I used Reflector to have a look at 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 has its inherited property set to false - which I think means that the methods we override will no longer have the attribute -- so, do we need to re-apply the attribute?


Yes, you have to re-apply the attribute because the ReliabilityContract has its inherited property set to false and that means methods in derived classes won't have the attribute applied.

Take a look at the below code. If you set the Inherited named parameter to false, the Method1 in the derived class does not have the attribute applied. After that, set the same parameter (Inherited) to true and run it again.

[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());
        }
    }
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜