该类型不能用作通用类型或方法"BaseController< T>"中的类型参数"T".没有隐式引用 [英] The type cannot be used as type parameter 'T' in the generic type or method 'BaseController<T>'. There is no implicit reference

查看:76
本文介绍了该类型不能用作通用类型或方法"BaseController< T>"中的类型参数"T".没有隐式引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个通用代码来简化我的代码(这是一个Web api项目),但是由于某种原因,它最终变得比我预期的要复杂.我正在尝试实现的是这样的:

I'm trying to create a generic to simplify my codes (it's a web api project), but at somehow it's ended up becoming more complicated than I expected. What I'm trying to implement is something like this:

为了简化我的整个真实代码,这是我写的:

To simplify my whole real code, this is what I've written:

public interface IDatabaseTable { }

public class ReceiptIndex: IDatabaseTable { }

public interface IBackend<T> where T: IDatabaseTable { }

public class Receipts : IBackend<ReceiptIndex> { }

public class Generic<T> : SyncTwoWayXI, IBackend<T> where T:IDatabaseTable { }

public class BaseController<T> : ApiController where T: IBackend<IDatabaseTable>, new () { }

以上所有行均在其自己的文件中单独创建.

All of the line above created separately in its own file.

当我尝试创建从BaseController继承的控制器时

When I try to create controller that Inherit from BaseController

public class ReceiptsBaseController : BaseController<Receipts>

我说错了

收据"类型不能用作通用类型或方法"BaseController".没有隐含的从收据"到"IBackend"的引用转换.

The type 'Receipts' cannot be used as type parameter 'T' in the generic type or method 'BaseController'. There is no implicit reference conversion from 'Receipts' to 'IBackend'.

我试图找到一个类似的问题,最后出现了一个叫做协方差和相反方差的问题.任何人都可以就我正在尝试做的事情提供反馈,或者可以做一些简化的事情.

I try to find a similar problem and end up with something called Covariance and Contravariance problem. Can anyone give feedback for what I'm trying to do or maybe something that can I do to simplify it.

推荐答案

您可以尝试在IBackend中指定 T .像这样:

You can try to specify the T in IBackend. Like this:

public class BaseController<T, TBackEndSubType> : ApiController
    where T : IBackend<TBackEndSubType>, new()
    where TBackEndSubType : IDatabaseTable { }

public class ReceiptsBaseController : BaseController<Receipts, ReceiptIndex> { }

这篇关于该类型不能用作通用类型或方法"BaseController&lt; T&gt;"中的类型参数"T".没有隐式引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆