覆寫連結要求應該與基底相同
更新:2007 年 11 月
型別名稱 |
OverrideLinkDemandsShouldBeIdenticalToBase |
CheckId |
CA2123 |
分類 |
Microsoft.Security |
中斷變更 |
中斷 |
原因
公用型別中之公用或保護的方法會覆寫方法或實作介面,而且沒有與介面或虛擬方法相同的連結要求。
規則描述
這項規則會使方法符合它的基底方法,即另一個型別中的介面或虛擬方法,然後比較每個方法上的連結要求。如果方法或基底方法具有連結要求,但另一個方法卻沒有,將會報告違規。
如果違反這項規則,則惡意呼叫端只需呼叫不安全的方法,就可以略過連結要求。
如何修正違規
若要修正此規則的違規情形,請將連結要求套用到沒有它的方法。
隱藏警告的時機
請勿隱藏此規則的警告。
範例
下列範例會顯示這項規則的各種違規。
using System.Security;
using System.Security.Permissions;
using System;
namespace SecurityRulesLibrary
{
public interface ITestOverrides
{
[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted=true)]
Object GetFormat(Type formatType);
}
public class OverridesAndSecurity : ITestOverrides
{
// Rule violation: The interface has security, and this implementation does not.
object ITestOverrides.GetFormat(Type formatType)
{
return (formatType == typeof(OverridesAndSecurity) ? this : null);
}
// These two methods are overridden by DerivedClass and DoublyDerivedClass.
[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted=true)]
public virtual void DoSomething()
{
Console.WriteLine("Doing something.");
}
public virtual void DoSomethingElse()
{
Console.WriteLine("Doing some other thing.");
}
}
public class DerivedClass : OverridesAndSecurity, ITestOverrides
{
// Rule violation: The interface has security, and this implementation does not.
public object GetFormat(Type formatType)
{
return (formatType == typeof(OverridesAndSecurity) ? this : null);
}
// Rule violation: This does not have security, but the base class version does.
public override void DoSomething()
{
Console.WriteLine("Doing some derived thing.");
}
// Rule violation: This has security, but the base class version does not.
[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted=true)]
public override void DoSomethingElse()
{
Console.WriteLine("Doing some other derived thing.");
}
}
public class DoublyDerivedClass : DerivedClass
{
// The OverridesAndSecurity version of this method does not have security.
// Base class DerivedClass's version does.
// The DoublyDerivedClass version does not violate the rule, but the
// DerivedClass version does violate the rule.
public override void DoSomethingElse()
{
Console.WriteLine("Doing some other derived thing.");
}
}
}