具体来说,我正在使用 EmguCV's Image
type .
我已经定义了一个接口(interface) ITransformation
,它带有一个方法 ApplyFrom
,它接受一个 Image
并返回一个 Image
:
public interface ITransformation
{
Image<TColor, TDepth> ApplyFrom<TColor, TDepth>(Image<TColor, TDepth> sourceImage);
}
但这对于类型参数来说似乎非常冗长,尤其是在使用该方法时。理想情况下,界面应如下所示:
public interface ITransformation
{
Image ApplyFrom(Image sourceImage);
}
但 Visual Studio 提示 Image
需要 2 个类型参数。我不想将 ApplyFrom()
方法绑定(bind)到特定的颜色或深度
我需要使用上面通用的、冗长的第一个版本吗?
或者我是否遗漏了两个版本之间的一些可能的中间地带?
最佳答案
Do I need to use the generic, verbose first version above?
是的——您需要在引用泛型类型时指定泛型参数。就像你不能引用 List
作为一种类型 - 您需要完全限定通用参数( List<T>
、 List<int>
等)
编译器可能能够在使用方法时推断通用参数,但声明必须在您拥有它们的所有三个位置包含通用参数。
关于减少冗长(并仍然保持函数通用)的唯一方法是缩短通用参数名称:
public interface ITransformation
{
Image<C, D> ApplyFrom<C, D>(Image<C, D> sourceImage);
}
您失去了泛型参数的 self 记录性质,但对编译器来说没有区别。
关于c# - 参数化返回类型是否需要泛型方法签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31301127/