Best way to accept a generic method argument [closed]

天涯浪子 提交于 2019-12-13 01:27:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!