gpt4 book ai didi

C# 使用泛型和接口(interface)实现

转载 作者:太空狗 更新时间:2023-10-29 18:02:20 25 4
gpt4 key购买 nike

上下文:.NET 4.0,C#

我正在创建一组接口(interface)和一组实现它们以提供某些服务的类。客户端使用具体的类,但调用使用接口(interface)作为参数类型声明的方法。

一个简化的例子是这个:

namespace TestGenerics
{
// Interface, of fields
interface IField
{
}

// Interface: Forms (contains fields)
interface IForm<T> where T : IField
{

}

// CONCRETE CLASES
class Field : IField
{
}

class Form <T> : IForm<T> where T : IField
{
}

// TEST PROGRAM
class Program
{
// THIS IS THE SIGNATURE OF THE METHOD I WANT TO CALL
// parameters are causing the error.
public static void TestMethod(IForm<IField> form)
{
int i = 1;
i = i * 5;
}

static void Main(string[] args)
{
Form<Field> b = new Form<Field>();
Program.TestMethod(b);
}
}
}

代码对我来说很有意义,但是我得到了编译器错误:

Argument 1: cannot convert from 'TestGenerics.Form<TestGenerics.Field>' to 'TestGenerics.IForm<TestGenerics.IField>' TestGenerics

我不确定我做错了什么,我在互联网上阅读了很多网页,但没有一个能解决我的问题。

是否有一种解决方案不会对我正在尝试构建的架构进行太多修改:

编辑:我设计接口(interface)的方式应使其独立于实现它们的具体类。具体的类可以从 dll 加载,但大多数应用程序都使用接口(interface)。在某些情况下,我需要使用具体的类,特别是在使用需要序列化的类时。

提前致谢。

亚历杭德罗

最佳答案

问题是 Form<Field>工具 IForm<Field>但不是 IForm<IField> .您不能将继承的类(或接口(interface))用作泛型参数,除非它被标记为与 out 协变。标识符。但是,将您的界面标记为协变会显着限制使用(基本上是在像 IEnumerable 这样的“仅输出”界面中制作),因此它可能对您不起作用。

让它工作的一种方法是制作TestMethod也通用:

public static void TestMethod<T>(IForm<T> form) where T:IField
{
int i = 1;
i = i * 5;
}

关于C# 使用泛型和接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17951049/

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