Answer the question
In order to leave comments, you need to log in
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("Вызван метод, определенный в классе");
}
}
static void Main(string[] args)
{
IBase instance1 = new Derived();
//так
Derived instance2 = (Derived)instance1;
instance2.MethodOnlyForDerivedClass();
//или так
((Derived)instance1).MethodOnlyForDerivedClass();
}
IBase instance1 = new Derived();
instance1.MethodOnlyForDerivedClass();
Answer the question
In order to leave comments, you need to log in
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
Surely something like this
var instance2 = instance1 as needClass
if(instance2 !=null)
{
instance2.doSomething();
}
*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
{
...
}
IFileStorage fs = new ExcelStorage
IExcelCellWriter xcw = fs as IExcelCellWriter;
if (xcw != null)
{
xcw.SetToCell(...
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question