I have a class implementing 2 different interfaces, both of them sharing a method signature, let's say 'int GetChildData()'. Both of them derive from the same base interface that contains another method, let's say 'int GetBaseData()' . The concrete class will explicitly implement the 2 child methods and implicitly implement the base method. When instantiating the class as a child interface and calling the base interface method, is it possible to retrieve from inside the called class which of the child interface was used to call the method?. Code will clarify this. Thank you
I cannot use implicit implementation because the two child interface implementation method need to have different logic.
internal class Program
{
public interface IBaseInt
{
int GetBaseData();
}
public interface IInterface_1 : IBaseInt
{
int getData();
}
public interface IInterface_2 : IBaseInt
{
int getData();
}
public class Class : IInterface_1, IInterface_2
{
public int GetBaseData()
{
//this.getData(); <--- this does not compile
//here i need to know if 'this' was created as IInterface_1 or as IInterface_2
if (/*???? what do i check ???*/true)
{
return (this as IInterface_1).getData();
}
else if (/*???? what do i check ???*/true)
{
return (this as IInterface_2).getData();
}
}
int IInterface_1.getData() => 1;
int IInterface_2.getData() => 2;
}
private static void Main(string[] args)
{
IInterface_1 int1 = new Class();
IInterface_2 int2 = new Class();
Console.WriteLine("int 1 : " + int1.GetBaseData());
Console.WriteLine("int 2 : " + int2.GetBaseData());
Console.ReadLine();
}
}
result should be '1' or '2' based on the interface used.
Aucun commentaire:
Enregistrer un commentaire