Implementing two interfaces or not?
I'm writing a class that returns both a DataTable and a IEnumerable. I cannot define the interface methods exactly the same except for return type. So, I wish I could create this interface (obviously, it doesn't compile):
interface IMyInterface
{
DataTable GetResults();
IEnumerable<string> GetResults();
}
So, how would you structure these two functions, rename them, multiple interfaces, parameters?
开发者_Go百科I'm just curious on how you guys would handle it, ty...
I would do this:
interface IMyInterface
{
DataTable GetResultsAsTable();
IEnumerable<string> GetResultsAsSequence();
}
Obviously C# doesn't allow you to have two methods whose signatures differ by return type only (interestingly the CLR does allow this). With that in mind I think it would be best to give the methods common prefixes and append a suffix that indicates the return type.
Can you do this?
interface IMyInterface {
DataTable GetDTResults();
IEnumerable<string> GetIEResults();
}
You could keep the same method name by using an out parameter:
interface IMyInterface
{
void GetResults(out DataTable results);
void GetResults(out IEnumerable<string> results);
}
I would rename the first method:
DataTable GetResultsDataTable();
Whether you do this as an interface or as a regular class this won't compile because you have two methods with the same name with the same parameterless signature.
Besides, returning method results using two very different types have really bad design implications.
精彩评论