简体   繁体   中英

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

Is there anyway in C# (I know Java allows this) that I can leave the abstract class empty implementing interfaces?

Nope. In C# the abstract class must fully implement the interface. Note it can implement it with abstract methods and abstract properties. It's one little thing about C# that has always bugged me.

The only way to do it is create virtual properties with no implementation. These are then overridden in your derived classes.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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