【问题标题】:The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'QueryAPI.Query<T>()类型“T”必须是引用类型才能将其用作泛型类型或方法“QueryAPI.Query<T>() 中的参数“T”
【发布时间】:2018-04-23 08:24:25
【问题描述】:

我正在编写一些代码,这些代码应该使用不同远程对象上的通用逻辑更新某些字段。因此我使用给定的 API。测试类是我自己的实现。其他两个类由 API 提供。 当我编写以下代码时,我得到了错误

The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'QueryAPI.Query<T>()

代码:

 public class Test<T> where T : class, UnicontaBaseEntity
    {
        private async Task Foo<T>(QueryAPI queryAPI, CrudAPI crudAPI, SyncSettings syncSettings)
        {
            Task<T[]> result = await queryAPI.Query<T>();
        }
    }

    public interface UnicontaBaseEntity : UnicontaStreamableEntity
    {
        int CompanyId { get; }

        Type BaseEntityType();
    }


    public class QueryAPI : BaseAPI
    {
        ...
        public Task<T[]> Query<T>() where T : class, UnicontaBaseEntity, new();
        ...
    }

对此有何想法?

提前致谢。

韩语 迈克

【问题讨论】:

标签: c#


【解决方案1】:

我会在这里从Foo() 中删除T,因为您的父类Test&lt;T&gt; 已经是通用的。

您还应该添加一个new() 约束,否则会出现另一个错误,因为 QueryAPI 需要一个具有默认构造函数的类型。

此外,包含Async 的一些重命名也是按顺序进行的。

public class Test<T> where T : class, UnicontaBaseEntity, new()
{
    private async Task FooAsync(QueryAPI queryAPI, CrudAPI crudAPI, SyncSettings syncSettings)
    {
        Task<T[]> result = await queryAPI.QueryAsync<T>();
    }
}

public interface UnicontaBaseEntity : UnicontaStreamableEntity
{
    int CompanyId { get; }

    Type BaseEntityType();
}


public class QueryAPI : BaseAPI
{
    ...
    public Task<T[]> QueryAsync<T>() where T : class, UnicontaBaseEntity, new()
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多