gpt4 book ai didi

c# - 通用接口(interface)

转载 作者:太空狗 更新时间:2023-10-29 21:07:19 25 4
gpt4 key购买 nike

这是我的代码

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com