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

屬性
規則識別碼 CA1061
職稱 不要隱藏基底類別方法
類別 設計
修正是造成中斷還是不中斷 中斷
在 .NET 10 中預設啟用 作為建議
適用語言 C# 與 Visual Basic

原因

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

規則描述

當衍生類型的方法的參數簽章僅在型別上比較弱衍生於基底類型的方法之參數簽章時,基底類型中的方法會被衍生類型中相同名稱的方法隱藏。

如何修正違規

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

隱藏警告的時機

請勿隱藏此規則的警告。

範例

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

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();

        // 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");
    }
}