在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 --我认为这意味着我们覆盖的方法将不再具有该属性--那么,我们需要重新应用该属性吗?
发布于 2011-10-29 14:12:04
是的,您必须重新应用该属性,因为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());
}
}
} https://stackoverflow.com/questions/3077329
复制相似问题