How to create a method or property in C # that is public but not inherited?

Here is an example. I have two classes, one is inherited, and both have a function with the same name, but different arguments:

public class MyClass
{
    //public class members

    public MyClass()
    {
        //constructor code
    }

    public void Copy(MyClass classToCopy)
    {
        //copy code
    } 
}

public class InheritedClass : MyClass
{
    //public class members

    public InheritedClass():base()
    {
        //constructor code
    }

    public void Copy(InheritedClass inheritedClassToCopy)
    {
        //copy code
    } 
}

My question is how to make the class copy method (MyClass.Copy) non-inherited or invisible in InheritedClass? I do not want to do this:

MyClass a;
InheritedClass b;
b.Copy(a);

Does this make sense, or should I keep this functionality there? Can I even ask to do?

+3
source share
5 answers

Does this make sense, or should I keep this functionality there? Can I even ask to do?

Trying to hide a public method like this when using a base class is problematic. You are intentionally trying to violate the Liskov signature principle .

alt text

+22

, ; # . ( )

, ; , , . ... ; , , .

+6

, . , , , :

public interface MyInterface
{
    void Copy(MyClass classToCopy)
}

public class MyClass : MyInterface
{
    void MyInterface.Copy(MyClass classToCopy)
    {
        //copy code
    } 
}
+4

. , . sealed, , .

+2

What everyone else said, but if I conclude correctly about my goal, make sure that InheritedClass users never use the MyClass method. In this case, exclude it from MyClass and create two classes that inherit it.

Make a MyBaseClass abstract if it should not be created (most likely).

(Edited - you probably want to include copy code for any part of the base class in the base class)

public abstract class MyBaseClass
{
    public MyClass()
    {
        //constructor code
    }
    protected void Copy(MyBaseClass classToCopy)
    {
        //copy code
    }
    // other methods that all inherited classes can use
}

public class MyClass: MyBaseClass
{
    public MyClass():base()
    {
        //constructor code
    }
    public void Copy(MyClass myClassToCopy)
    {
        base.Copy(myClassToCopy);
        //specific copy code for this extensions in this class
    } 
}

public class InheritedClass : MyBaseClass
{
    public InheritedClass():base()
    {
        //constructor code
    }
    public void Copy(InheritedClass inheritedClassToCopy)
    {
        base.Copy(myClassToCopy);
        //specific copy code for this extensions in this class
    } 
}
+1
source

Source: https://habr.com/ru/post/1771361/


All Articles