已知类型属性不能使用类型参数

Mis*_*pic 6 c# asp.net asp.net-web-api

我有这个 Web Api 控制器操作:

public Plant<TissueProductionLine> GetPlant(string plant, string range)
{
    return _repo.GetPlant(plant, range);
}
Run Code Online (Sandbox Code Playgroud)

启动这个我得到这个:

不应键入数据合同名称为“IGMProdLineDashboard.Models”的“IGMProdLineDashboard.Models.TissueProductionLineGroup”。考虑使用 DataContractResolver 或将任何静态未知的类型添加到已知类型列表中 - 例如,通过使用 KnownTypeAttribute 属性或将它们添加到传递给 DataContractSerializer 的已知类型列表中。

好的,没问题,我将Plant[KnownType]属性装饰我的对象并指定非原始属性:

[KnownType(typeof(ProductionLineGroups<T>))]
public class Plant<T>: IPlant<T> where T : IProductionLine
{
    public Plant ()
    {
        ProductionLineGroups = new ProductionLineGroups<T>();
    }
    public ProductionLineGroups<T> ProductionLineGroups { get; set; }
Run Code Online (Sandbox Code Playgroud)

现在我得到一个编译时错误:

'IGMProdLineDashboard.Models.ProductionLineGroups':属性参数不能使用类型参数

重读第一条消息,它想知道派生类型: TissueProductionLineGroup

如果我Plant用这个装饰我的对象,一切正常:

[KnownType(typeof(TissueProductionLineGroup))]
Run Code Online (Sandbox Code Playgroud)

显然,这里的含义是我Plant现在需要了解所有不同类型的生产线,这意味着Plant每当添加新组时我都需要更新。

有没有办法解决?

小智 10

不幸的是,错误消息根本不会误导您。属性不能使用泛型类型参数。据我所知,这个问题没有办法解决。

Jon Skeet 之前就此事发表过回答,并表示 C# 团队选择添加此限制是为了使编译器代码更简单,尽管 CLI 没有理由不能表示通用属性。

请参阅:/sf/answers/20598161/

  • 是的,我看到它也变得有点热了。不幸的是,这种情况正在耦合我的代码,我一直在努力保持解耦...... (4认同)