开发者

Interface and base class mix, the right way to implement this

I have some user controls which I want to specify properties and methods for.

They inherit from a base class, because they all have properties such as "Foo" and "Bar", and the reason I used a base class is so that I dont have to manually implement all of these properties in each开发者_StackOverflow中文版 derived class.

However, I want to have a method that is only in the derived classes, not in the base class, as the base class doesn't know how to "do" the method, so I am thinking of using an interface for this. If i put it in the base class, I have to define some body to return a value (which would be invalid), and always make sure that the overriding method is not calling the base. method

Is the right way to go about this to use both the base class and an interface to expose the method? It seems very round-about, but every way i think about doing it seems wrong...

Let me know if the question is not clear, it's probably a dumb question but I want to do this right.

EDIT : Thanks to all the people with your excellent abstract suggestions, but this breaks the designer. If abstract was not a selectable option, what would you do?


Alternatively you could define the method as 'abstract' in the base class, which will not require the class to implement it. For example:

abstract class A
{
   public abstract void B();
}

Of course this will force your base class to be abstract as well, but it sounds like this would work just fine for you.

See Abstract methods on MSDN.

Update

Since abstract is not an option for you due to designer issues, you could just define the method as part of your base class, and have it throw a NotImplementedException if it is called directly from the base class:

void DerivMethod()
{
    // Must be implemented by derived class
    throw new NotImplementedException();
}

Otherwise, using an interface would be fine, especially if the above leaves a bad taste in your mouth...


You should make your base class an Abstract class. Then the base class can implement the Interface by marking the method abstract.

http://msdn.microsoft.com/en-us/library/aa664435(VS.71).aspx


Mark the method as abstract in your base class. You'll be forced to implement it in the derived classes, but the base class will not need to have a method definition.


I agree with with others, but making your user control abstract has some issues for the designer. The designer will often not display the abstract user control.

I would implement the interface methods in the base class. You can throw a NotImplemented exception or Assert.Fail in the methods if you want to make sure the inheritors are overriding these methods properly.


Declare the function signature in the base class and use the "abstract" modifier.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜