Редактиране

Споделяне чрез


CA1061: Do not hide base class methods

Property Value
Rule ID CA1061
Title Do not hide base class methods
Category Design
Fix is breaking or non-breaking Breaking
Enabled by default in .NET 8 As suggestion

Cause

A derived type declares a method with the same name and with the same number of parameters as one of its base methods; one or more of the parameters is a base type of the corresponding parameter in the base method; and any remaining parameters have types that are identical to the corresponding parameters in the base method.

Rule description

A method in a base type is hidden by an identically named method in a derived type when the parameter signature of the derived method differs only by types that are more weakly derived than the corresponding types in the parameter signature of the base method.

How to fix violations

To fix a violation of this rule, remove or rename the method, or change the parameter signature so that the method does not hide the base method.

When to suppress warnings

Do not suppress a warning from this rule.

Example

The following example shows a method that violates the rule.

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