接受泛型方法参数的最佳方式 [英] Best way to accept a generic method argument
问题描述
我看到了两种创建界面的方法。
public interface IService< T>其中T:class
{
void Action< TSource>(int id,TSource source,Action< T> action)
where TSource:IRead< T>
}
与
public interface IService< T>其中T:class
{
void Action(int id,IRead< T> source,Action< T> action);
}
那么,哪一个最好?为什么?
我会在这边出去,说第二个更好。
第一个定义允许您在实现Action时直接使用TSource(而不是通过它必须实现的接口IRead)。现在,我可以想象得到的唯一的好处就是在你的函数签名中使用TSource,而你并没有这样做。即类似于:
TSource MyAction< TSource>(int id,TSource source,Action< T,TSource> action)
where TSource:IRead< T>; // TSource现在也从我们的方法中返回
在任何其他情况下, MyAction的主体(请注意,我冒昧地将您的示例方法重命名为不与System.Action冲突),以仅知道和使用IRead接口。
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?
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.
这篇关于接受泛型方法参数的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!