c# - 通用接口(interface)

标签 c# generics interface generic-interface

这是我的代码

public interface ITranslator<E, R>
{       
    E ToEntity<T>(R record);
}

class Gens : ITranslator<string, int>
{
    #region ITranslator<string,int> Members

    public string ToEntity<MyOtherClass>(int record)
    {
        return record.ToString();
    }

    #endregion
}

当我编译它时,我得到一个错误 Type parameter declaration must be an identifier not a type

为什么我不能拥有ToEntity<MyOtherClass>但只能有ToEntity<T> ??

编辑:什么是MyOtherClass正在做 ?我正在为多个表/类在实体(相当于 Entity Framework 的 POCO)和记录(框架返回的对象)之间进行转换。所以我想用它来做我的类(class)特定的转换

最佳答案

你的接口(interface)有一个通用的 ToEntity<T> 方法,你在你的实现类 Gens 中把它变成了非通用的 ToEntity<MyOtherClass> 。 (泛型 方法可以采用任何类型参数,可能给定 T 的某些约束。您的 Gens 类试图提供 ToEntity 的定义仅针对类型参数 MyOtherClass,这违背了泛型的目的。)

在您的代码示例中,不清楚您的 Gens 类是如何尝试使用 MyOtherClass 类型的;它当然不涉及 ToEntity 的逻辑。我们需要更多信息才能进一步指导您。

为了说明,这是您当前对 ITranslator<E, R> 接口(interface)的定义,用简单的英语表示:

"I provide a mechanism to translate any record of type R into an entity of type E, this mechanism being dependent upon any user-specified type T."

另一方面,您的 Gens 类,按照它当前的设计方式,“实现”了上述接口(interface),如下所示:

"I can translate integers to strings. I provide the illusion of allowing the user to specify a type to control how this translation is performed, but in fact there is no choice of type. The MyOtherClass class is involved somehow; that's all I can say."

从这两个描述中,很明显 Gens并没有真正执行 ITranslator<E, R> 接口(interface)保证的事情。即,它不愿意为其 ToEntity 方法接受用户指定的类型。这就是此代码无法为您编译的原因。

关于c# - 通用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2166037/

相关文章:

c# - Visual Studio 设计器加载失败

c# - 我如何将更多时间添加到 datetime.now 解析它然后重置回原始 datetime.now?

c# - 单击事件未触发 - 无法更改焦点 - 无法关闭表单

c# - 在 C# 中检查泛型方法的类型参数

c# - 将 c# 代码评估为 aspx 文件中的字符串

Typescript 类型的通用和非通用版本

Delphi - 免费泛型

interface - Typescript:使用单个函数与其他 JavaScript 库一起使用

java - 在java 8中模拟私有(private)接口(interface)

java - 用Java中的接口(interface)隐藏api