Answer the question
In order to leave comments, you need to log in
What's wrong with interface inheritance?
I'm learning about interface inheritance. When compiling this code:
using System;
public class Test
{
public static void Main()
{
Lol l = new Lol();
Console.WriteLine(((IParent)l).Family);
Console.WriteLine(((IChild)l).Family);
Console.WriteLine(l.Name);
}
}
public interface IParent
{
string Family { get; }
}
public interface IChild : IParent
{
string Name { get; }
}
public class Lol : IChild
{
string IParent.Family { get { return "suck"; } }
string IChild.Family { get { return "duck"; } }
public string Name { get { return "ross"; } }
}
Answer the question
In order to leave comments, you need to log in
You didn't specify that Lol implements the IParent interface
. Also, you probably wanted to add a Family property to IChild.
After updating the code:
You are using an explicit implementation of the interface, but IChild does not have its own Family property, only inherited from IParent. You can just learn the new keyword from properties.
Perhaps what you want to see is done like this:
using System;
public class Test
{
public static void Main()
{
Lol l = new Lol();
Console.WriteLine(((IParent)l).Family);
Console.WriteLine(((IChild)l).Family);
Console.WriteLine(l.Name);
Console.ReadLine ();
}
}
public class IParent
{
public string Family { get { return "suck"; } }
}
public class IChild : IParent
{
public string Family { get { return "duck"; } }
}
public class Lol : IChild
{
public string Name { get { return "ross"; } }
}
// Вывод:
// suck
// duck
// ross
public class Lol : IChild, IParent // !!!
{
string IParent.Family { get { return "suck"; } }
string IChild.Family { get { return "duck"; } }
public string Name { get { return "ross"; } }
}
There is a small exception when you explicitly implement interfaces, C# expects you to specify derived interface names, not interface names that might be inherited from another interface.
In your case, IChild does not contain a Family field, which is why you get the 'accessor not found' error.
The essence of the explicit interface implementation is the explicit use of interface names, without regard to the base interface.
You can do the following.
public interface IChild : IParent
{
new string Family { get; }
string Name { get; }
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question