【问题标题】:There is no boxing conversion from "int" to 'T'没有从“int”到“T”的装箱转换
【发布时间】:2018-06-20 13:50:08
【问题描述】:

我有一个通用方法:

public JobKey Queue<TRequest>(TRequest request) where TRequest : IJobRequest{}

IJobRequest:

 public interface IJobRequest
    {

    }

接下来,在foreach循环中我要调用Queue&lt;&gt;()泛型方法:

foreach (var item in campaigns)
                {
                    _jobScheduler.Queue<>();
                }

“item”变量是我的自定义类型“Campaign”,并且有一个属性int Id

foreach 循环中,我想将item.Id 类似参数传递给Queue&lt;&gt;() 方法。

_jobScheduler.Queue<int>(item.Id);

我应该在interface IJobRequest 中进行哪些更改才能这样做:_jobScheduler.Queue&lt;int&gt;(item.Id); 因为现在我有一个错误:“没有从“int”到“IJobRequest”的装箱转换”

【问题讨论】:

  • 答案正是它所说的。您指定参数必须实现IJobRequestint 没有实现 IJobRequest。最简单的解决方法是将行更改为 public JobKey Queue&lt;TRequest&gt;(int id) where TRequest : IJobRequest{}
  • @DavidStockinger:我同意你的说法,尽管此时可以完全删除 Generic 参数,这让我们所有人都想知道它首先在那里做了什么......

标签: c# generics inheritance interface cycle


【解决方案1】:

您有约束TRequest : IJobRequest,这意味着类型参数应该继承/实现接口IJobRequest,并且显然int 类型不会从该接口继承。

您需要创建一个从该接口继承的类型,然后您可以将该类型用作方法调用中的参数。

作为一个例子来证明它会是这样的:

public class MyType : IJobRequest
{

}

然后:

 MyType instance = new MyType();
_jobScheduler.Queue<MyType>(instance);

您还需要在类型参数上应用new() constraint 以允许使用具有无参数构造函数的类型。

或者,您可以删除通用参数的约束:

public JobKey Queue<TRequest>(TRequest request)

希望它能给你一些想法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2016-06-30
    • 2011-02-27
    相关资源
    最近更新 更多