MyGeneric1[T] 上的 GenericArguments[0]、TestClass 违反了类型参数“T”的约束

问题描述 投票:0回答:1

我正在尝试按照这篇博客文章创建一个扩展 ODataController 的通用控制器。 https://blog.scottlogic.com/2015/12/01/generalizing-odata.html但我目前遇到标题中所述的类型错误。

我尝试使用没有实体框架注释的基本类。还内置了类类型。

通用控制器.cs

public class GenericController<T> : ODataController where T: class, IIndexedModel
{
  ...
}

MyControllerSelector.cs

public class MyControllerSelector : IHttpControllerSelector
{
    private IDictionary<string, HttpControllerDescriptor> _controllerMappings;

    public EntityControllerSelector(
        HttpConfiguration config, IEnumerable<EntitySetConfiguration> entitySets)
    {
        _controllerMappings = GenerateMappings(config, entitySets);
    }

    public IDictionary<string, HttpControllerDescriptor> GenerateMappings(
        HttpConfiguration config, IEnumerable<EntitySetConfiguration> entitySets)
    {
        IDictionary<string, HttpControllerDescriptor> dictionary =
            new Dictionary<string, HttpControllerDescriptor>();

        foreach (EntitySetConfiguration set in entitySets)
        {
             // !!! This throws the type exception !!!
            var genericControllerDescription =
               new HttpControllerDescriptor(config, set.Name,
                   typeof(GenericController<>).MakeGenericType(set.ClrType));

            dictionary.Add(set.Name, genericControllerDescription);
        }

        return dictionary;
    }

    public HttpControllerDescriptor SelectController(HttpRequestMessage request)
    {
        var path = request.RequestUri.LocalPath.Split('/', '(');
        return _controllerMappings[path[1]];
    }

    public IDictionary<string, HttpControllerDescriptor> GetControllerMapping()
    {
        return _controllerMappings;
    }
}

编辑以获取更多信息: 测试类.cs

public class TestClass :IIndexedModel {
    public int Id {get; set;}
}

索引模型.cs

public interface IIndexedModel {
    int Id { get; set;}
}

我尝试对不同的类进行硬编码,而不是 set.ClrType,它们都抛出相同的异常。

System.ArgumentException: 'GenericArguments[0], '...TestClass', on '...GenericController`1[T]' 违反了类型 'T' 的约束。'

内部异常

TypeLoadException: GenericArguments[0], '...TestClass', on '...GenericController`1[T]' 违反了类型参数 'T' 的约束。

c# generics
1个回答
3
投票

您传递给的类型

T

typeof(GenericController<>).MakeGenericType(typeof(T))

必须是一个根据约束

IIndexedModel
实现
where T : class, IIndexedModel
的类。

确保

IIndexedModel
与类型约束中提到的
IIndexedModel
相同。它可能是具有相同名称但驻留在另一个命名空间或程序集中的类型。

© www.soinside.com 2019 - 2024. All rights reserved.