C# How to implement interface where concrete classes differs?
First, sorry for the vaque title, but I don't know a good title for my question.
In my application I use criteria. The criteria can be seen as controls. I have textboxes, but also radio buttons and check boxes.
I use interfaces to achieve this:
ICriteria is the base interface where all criteria classes inherits from.
Text开发者_运维百科Type inherits from ICriteria. RadioType also inherits from ICriteria. But, RadioType must have choices.
Both, TextType and RadioType do have some properties which are the same.
My problem is, I don't know exactly how to implement this. I mean, I can add some methods and properties to ICriteria which affects choices, but then TextType has to inherit these methods and properties too. I don't think this is nice because TextType doesn't have choices.
What is the best way to implement this?
why not use a hierarchy of interfaces
public interface ICriteria
{
void SomeCriteriaMethod();
}
public interface IChoices : ICriteria
{
void SomeChoicesMethod();
}
and then use it like this
foreach (ICriteria criteria in criterias)
{
// something
var choice = criteria as IChoices;
if (choice != null)
// do something else
}
There are two options here:
You could have two different interfaces (or ISomeMoreAdvancedInterface : ISomeBasicInterface
) - where one interface allows the simple scenarios, and the second interface has extra methods for obtaining the options.
Or: you can have methods like (to copy from TypeConverter
) GetStandardValuesSupported
- if this returns true
it is reasonable to call the GetStandardValues
method; if this returns false the caller should not call GetStandardValues
(and it will probably throw a NotSupportedException
, but a well-written caller should never see them because they are observing *Supported
).
With lack of details it's hard to be sure but looks like you try to mix presentation layer and business logic in one class. May be will be better to have ICriteriaEditor interface that will contains ICriteria as property and Factory that will create proper ICriteriaEditor objects depends of ICriteria type. Anyway you have to be more specific in details.
精彩评论