【问题标题】:When inheriting from SafeHandle, should we reapply the ReliabilityContract attribute?从 SafeHandle 继承时,我们是否应该重新应用 ReliabilityContract 属性?
【发布时间】:2014-11-11 18:22:50
【问题描述】:

在 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——我认为这意味着我们覆盖的方法将不再具有该属性——那么,我们是否需要重新应用该属性?

【问题讨论】:

  • 您承诺您已经测试了您的代码并验证它不会破坏依赖于关键终结器的自定义 CLR 主机的状态。你是否?如果您实际上没有在这样的主机上运行(实际上是 SQL Server),那么这并不重要。
  • 昨天在同一主题上遇到了一些困难,我想补充以下几点:SafeHandle 的源代码(截至本文撰写时)指出 每个方法 i> 你从ReleaseHandle() 调用(不仅是关闭句柄的本机方法)应该有ReliabilityContract。另请注意,句柄并非必要被本机方法关闭;但即使它们被托管方法关闭,托管方法也应该有ReliabilityContract

标签: c# pinvoke


【解决方案1】:

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

看看下面的代码。如果将Inherited 命名参数设置为false,则派生类中的Method1 没有应用该属性。之后,将相同的参数(Inherited)设置为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());
        }
    }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 2010-12-12
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 2018-06-01
    相关资源
    最近更新 更多