【问题标题】:Multiple constraint on type parameter类型参数的多重约束
【发布时间】:2014-07-07 14:39:58
【问题描述】:

我做了这个多重约束

public class BaseValidation<S, R> 
        where R : BaseRepository 
        where S : BaseService<R>, new()
    {
        public S service;

        public BaseValidation()
        {
            service = new S();
        }
    }

这是 BaseService 类

public class BaseService<T> where T : BaseRepository, new(){ }

当我构建时,会发生这样的错误......

'R' 必须是具有公共无参数的非抽象类型 构造函数,以便将其用作泛型类型中的参数“T”

如何正确地做到这一点? 谢谢。

【问题讨论】:

  • BaseService 有无参数构造函数吗?

标签: c# generics type-constraints


【解决方案1】:

您还需要将new() 约束添加到R,因为TBaseService&lt;T&gt; 的定义中具有该约束:

public class BaseValidation<S, R> 
        where R : BaseRepository, new()
        where S : BaseService<R>, new()
{
    public S service;

    public BaseValidation()
    {
        service = new S();
    }
}

如果您实际上不需要 BaseService&lt;T&gt; 中的该约束,只需将其删除即可。

【讨论】:

    猜你喜欢
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多