接受泛型方法参数的最佳方法

时间:2012-10-26 09:57:12

标签: c# generics methods interface repository

我有一个界面,它描述了在某些存储库中查找的某个项目上执行某些操作的方法。

我看到了两种创建界面的方法。

public interface IService<T> where T : class
{
    void Action<TSource>(int id, TSource source, Action<T> action)
        where TSource : IRead<T>;
}

public interface IService<T> where T : class
{
    void Action(int id, IRead<T> source, Action<T> action);
}

那么,哪一个最好,为什么?

1 个答案:

答案 0 :(得分:2)

我会站在这里,并说第二个更好。

第一个定义允许您在Action的实现中直接使用TSource(而不是通过它必须实现的接口IRead)。现在,我可以想象的唯一好处就是在你的函数签名中使用TSource,你不会这样做。例如:

TSource MyAction<TSource>(int id, TSource source, Action<T, TSource> action)
        where TSource : IRead<T>; // TSource is now also returned from our method

在任何其他情况下,MyAction的主体(注意我冒昧地重命名你的示例方法不与System.Action冲突)只会知道并使用IRead接口会好得多。

相关问题