Is inheritance in a C # question an override of internal methods?

Is it possible to override the behavior of an internal method?

using System;

class TestClass
{
    public string Name { get { return this.ProtectedMethod(); } }

    protected string ProtectedMethod()
    {
        return InternalMethod();
    }

    string InternalMethod()
    {
        return "TestClass::InternalMethod()";
    }
}

class OverrideClassProgram : TestClass
{   // try to override the internal method ? (doesn't work)        
    string InternalMethod()
    {
        return "OverrideClassProgram::InternalMethod()";
    }

    static int Main(string[] args)
    {
        // TestClass::InternalMethod()
        Console.WriteLine(new TestClass().Name);
        // TestClass::InternalMethod() ?? are we just screwed?
        Console.WriteLine(new OverrideClassProgram().Name); 
        return (int)Console.ReadKey().Key;
    }
}
+3
source share
5 answers

I think you got something confused here. There is the actual keyword "internal", is that what you want?

internal string InternalMethod()
{
    return "TestClass::InternalMethod()";
}

But I think what you're really looking for is a “virtual” keyword. This allows you to override: Parent class

protected virtual string InternalMethod()
{
    return "TestClass::InternalMethod()";
}

Kids class

protected override string InternalMethod()
{
    return "TestProgram::InternalMethod()";
}

Using the keyword "new" is valid, but it completely repeats the method. That is, it destroys polymorphism.

Edit: Here is the link.

+4
source

Java , /. # , . , .

, , ( , ), InternalMethod() , , .

, , , .

+2

, cent.

Internal , . , , public .

MSDN ,

, . , , . , ,

0

override... - constuctor

-1

Of course, this is possible, but to override the method, the method must be virtualor abstract, like any other appearance.

class Base
{
    internal virtual void Foo()
    {
        Console.WriteLine("Foo from Base");
    }
}

class Derived : Base
{
    internal override void Foo()
    {
        Console.WriteLine("Foo from Derived");
    }
}

When you use a keyword new, it calls the hiding method , which is not the same. If I write this:

class Base
{
    internal void Foo()
    {
        Console.WriteLine("Foo from Base");
    }
}

class Derived : Base
{
    internal new void Foo()
    {
        Console.WriteLine("Foo from Derived");
    }
}

static void Main()
{
    Base b = new Derived();
    b.Foo();
}

Then he will execute the method Base Foo, not Derived. In other words, it will print Foo from Base. In the first case, he would still execute the method Derivedand print Foo from Derived.

-1
source

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


All Articles