CA1061:不要隱藏基底類別方法

屬性
規則識別碼 CA1061
標題 不要隱藏基底類別方法
類別 設計
修正程式是中斷或非中斷 中斷
預設在 .NET 8 中啟用 建議

原因

衍生型別會宣告名稱相同的方法,且參數數目與其中一個基底方法相同;一或多個參數是基底方法中對應參數的基底類型;和任何其餘參數的類型都與基底方法中的對應參數相同。

檔案描述

當衍生方法的參數簽章只與基底方法參數簽章中的對應型別不同時,基底型別中的方法會隱藏相同具名的方法。

如何修正違規

若要修正此規則的違規,請移除或重新命名方法,或變更參數簽章,讓方法不會隱藏基底方法。

隱藏警告的時機

請勿隱藏此規則的警告。

範例

下列範例顯示違反規則的方法。

class BaseType
{
    internal void MethodOne(string inputOne, object inputTwo)
    {
        Console.WriteLine("Base: {0}, {1}", inputOne, inputTwo);
    }

    internal void MethodTwo(string inputOne, string inputTwo)
    {
        Console.WriteLine("Base: {0}, {1}", inputOne, inputTwo);
    }
}

class DerivedType : BaseType
{
    internal void MethodOne(string inputOne, string inputTwo)
    {
        Console.WriteLine("Derived: {0}, {1}", inputOne, inputTwo);
    }

    // This method violates the rule.
    internal void MethodTwo(string inputOne, object inputTwo)
    {
        Console.WriteLine("Derived: {0}, {1}", inputOne, inputTwo);
    }
}

class Test
{
    static void Main1061()
    {
        DerivedType derived = new DerivedType();

        // Calls DerivedType.MethodOne.
        derived.MethodOne("string1", "string2");

        // Calls BaseType.MethodOne.
        derived.MethodOne("string1", (object)"string2");

        // Both of these call DerivedType.MethodTwo.
        derived.MethodTwo("string1", "string2");
        derived.MethodTwo("string1", (object)"string2");
    }
}