问题
I got a interface which describes a way to do some action on some item which is looked up in some repository.
And i see two ways to create that interface.
public interface IService<T> where T : class
{
void Action<TSource>(int id, TSource source, Action<T> action)
where TSource : IRead<T>;
}
versus
public interface IService<T> where T : class
{
void Action(int id, IRead<T> source, Action<T> action);
}
So, which one is the best and why?
回答1:
I will go out on a limb, here, and say that the second one is better.
The first definition would allow you to use TSource directly (and not through the interface IRead that it's bound to implement) in your implementation of Action. Now, the only good use I can imagine for that would be using TSource in the signature of your function, which you're not doing. i.e. something like:
TSource MyAction<TSource>(int id, TSource source, Action<T, TSource> action)
where TSource : IRead<T>; // TSource is now also returned from our method
In any other case, it would be much better for the body of MyAction (note that I took the liberty to rename your example method not to conflict with System.Action) to only know and use the IRead interface.
来源:https://stackoverflow.com/questions/13084702/best-way-to-accept-a-generic-method-argument