简体   繁体   English

C#接口由空抽象类实现

[英]C# Interface implemented by empty abstract class

Can I leave an abstract class that implements interfaces empty and imply that all the methods/properties in the interface are abstract within my class. 我可以留下一个实现接口为空的抽象类,并暗示接口中的所有方法/属性都是我的类中的抽象。 It appears that I have to write them out again in the abstract class but I really want to avoid this duplication. 看来我必须在抽象类中再次写出来,但我真的想避免这种重复。

My reason is I have a couple of interfaces with different accessors, one public and one internal, that I want to bring together so I have an abstract class that implements them both that can then be extended. 我的理由是我有几个带有不同访问器的接口,一个是公共的,一个是内部的,我想把它们放在一起所以我有一个抽象类来实现它们,然后可以扩展它们。

public interface ISomePublicProperties {
    int PropertyOne {get;}
}

internal interface ISomeInternalProperties {
    int PropertyTwo {get;}
}

public abstract class SomeClass : ISomePublicProperties, ISomeInternalProperties {}

But the compiler complains that SomeClass does not implement interface method ISomePublicProperties.PropertyOne and ISomeInternalProperties.PropertyTwo 但编译器抱怨SomeClass没有实现接口方法ISomePublicProperties.PropertyOne和ISomeInternalProperties.PropertyTwo

Is there anyway in C# (I know Java allows this) that I can leave the abstract class empty implementing interfaces? 无论如何在C#中(我知道Java允许这样)我可以将抽象类留空实现接口吗?

Nope. 不。 In C# the abstract class must fully implement the interface. 在C#中,抽象类必须完全实现接口。 Note it can implement it with abstract methods and abstract properties. 请注意,它可以使用抽象方法和抽象属性实现它。 It's one little thing about C# that has always bugged me. 关于C#的一件小事总是让我烦恼。

The only way to do it is create virtual properties with no implementation. 唯一的方法是创建没有实现的virtual属性。 These are then overridden in your derived classes. 然后在派生类中重写它们。

public abstract class SomeClass : ISomePublicProperties, ISomeInternalProperties 
{
    public abstract int PropertyOne { get; }
    internal abstract int PropertyTwo { get; }
}

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

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