K
K
kykyryky2016-08-11 10:10:42
Programming
kykyryky, 2016-08-11 10:10:42

How to call a method of a derived class that is not declared in an interface?

There is the following class structure:

interface IBase
    {
        void Method();
    }
    class Derived : IBase
    {
        public void Method() //реализация метода из интерфейса
        {
            Console.WriteLine("Вызван метод, определенный в интерфейсе");
        }
        public void MethodOnlyForDerivedClass() //определение метода, нужного только в Derived
        {
            Console.WriteLine("Вызван метод, определенный в классе");
        }
    }

main:
static void Main(string[] args)
        {
            IBase instance1 = new Derived();

            //так
            Derived instance2 = (Derived)instance1;
            instance2.MethodOnlyForDerivedClass();

            //или так
            ((Derived)instance1).MethodOnlyForDerivedClass();
        }

How to build a hierarchy to make it easier to call methods of only a derived class? For example like this:
IBase instance1 = new Derived();
instance1.MethodOnlyForDerivedClass();

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
GavriKos, 2016-08-11
@kykyryky

If a method is not declared in a class/interface, it cannot be called from outside. Unless you get the descendants with reflection, but this will already be a different class.
In your case, there are two options - declare a method in the interface or make the instance1 variable of the Derived type. You can also do type casting, but this is bug-dangerous

D
Dmitry Kovalsky, 2016-08-11
@dmitryKovalskiy

Surely something like this

var instance2 = instance1 as needClass
if(instance2 !=null)
{
instance2.doSomething();
}

But the idea is below average. Move away from a spherical problem in a vacuum and formulate a problem. Then there might be a nice solution.

A
Alexey Shumkin, 2016-08-11
@ashumkin

*I wrote above from my mobile, so I'll add more details:

interface IFileStorage {
  void LoadFromFile();
}
interface IExcelCellWriter {
  void SetToCell(int i, int j, string value);
}
class ExcelStorage : IFileStorage, IExcelCellWriter
{
...
}

and then use:
IFileStorage fs = new ExcelStorage
IExcelCellWriter xcw = fs as IExcelCellWriter;
if (xcw != null)
{
  xcw.SetToCell(...
  ...
}

Z.Y. I don't write in C#, so I looked at "casting to another interface" here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question