简体   繁体   English

C#实现接口和继承

[英]C# Implement Interface and inheritance

I'm trying to implment a property interface with a class inherit the declare one. 我试图用继承声明的类来实现属性接口。 Maybe the example is more easy to understand. 也许这个例子更容易理解。

MyClassA is OK, but MyClassB has a compile error 'Test.MyClassB' does not implement interface member 'Test.IMyInterface.PropA'. MyClassA可以,但是MyClassB有一个编译错误'Test.MyClassB'没有实现接口成员'Test.IMyInterface.PropA'。 Any Idea how I can do this? 知道我该怎么做吗?

/****** EDITED CODE ******/ / ******编辑代码****** /

public class BaseClass
{
    public int PropA { get; set; }
}

public class InheritClass : BaseClass
{
    public int PropB { get; set; }
}

public interface IMyInterface
{
    BaseClass PropClass { get; set; }
}


public class MyClassA : IMyInterface
{

    public BaseClass PropClass { get; set; }
}

public class MyClassB : IMyInterface
{

    public InheritClass PropClass { get; set; }
}

this is what you should do 这是你应该做的

public class BaseClass
{
    public int PropA { get; set; }
}

public class InheritClass : BaseClass
{
    public int PropB { get; set; }
}

public interface IMyInterface
{
    BaseClass PropClass { get; set; }
}


public class MyClassA : IMyInterface
{

    public BaseClass PropClass { get; set; }
}

public class MyClassB : IMyInterface
{
    private BaseClass _propClass;

    public BaseClass PropClass
    {
        get { return (InheritClass)_propClass; }
        set { _propClass = (InheritClass)value; }
    }
}

this is not directly possible, also why you are trying to do this. 这不是直接可能的,也是您尝试这样做的原因。 if you have base class you can use its child to set or get... 如果您有基类,则可以使用其子类来设置或获取...

Your interface requires that all classes that implement it have the property int PropA { get; set; } 您的接口要求所有实现接口的类都具有int PropA { get; set; }属性int PropA { get; set; } int PropA { get; set; } int PropA { get; set; } , but your class MyClassB doesn't have this method yet is inheriting IMyInterface . int PropA { get; set; } ,但您的类MyClassB还没有此方法正在继承IMyInterface

So you have two options. 因此,您有两个选择。

One, just implement the interface: 一,只需实现接口:

public class MyClassB : IMyInterface
{
    public int PropA { get; set; }
    public int PropB { get; set; }
}

Or, two, if you wish to only expose PropB on MyClassB then you could explicitly implement the interface (and assuming that PropB should be the implementation) then you would do this: 或者,两个,如果您只希望在MyClassB上公开PropB ,则可以显式实现该接口(并假定应该是PropB的实现),则可以这样做:

public class MyClassB : IMyInterface
{
    int IMyInterface.PropA { get { return this.PropB; } set { this.PropB = value; } }
    public int PropB { get; set; }
}

You should add PropA in implements of MyClassB: 您应该在MyClassB的实现中添加PropA

public class MyClassB : IMyInterface
{
**public int PropA { get; set; }**
public int PropB { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM