我对泛型的了解越来越深,现在我需要帮助。我得到一个编译错误的'派生'类如下所示的主题标题。我看到许多其他类似的帖子,但我没有看到它们之间的关系。谁能告诉我怎么解决这个问题?

using System;
using System.Collections.Generic;


namespace Example
{
    public class ViewContext
    {
        ViewContext() { }
    }

    public interface IModel
    {
    }

    public interface IView<T> where T : IModel 
    {
        ViewContext ViewContext { get; set; }
    }

    public class SomeModel : IModel
    {
        public SomeModel() { }
        public int ID { get; set; }
    }

    public class Base<T> where T : IModel
    {

        public Base(IView<T> view)
        {
        }
    }

    public class Derived<SomeModel> : Base<SomeModel> where SomeModel : IModel
    {

        public Derived(IView<SomeModel> view)
            : base(view)
        {
            SomeModel m = (SomeModel)Activator.CreateInstance(typeof(SomeModel));
            Service<SomeModel> s = new Service<SomeModel>();
            s.Work(m);
        }
    }

    public class Service<SomeModel> where SomeModel : IModel
    {
        public Service()
        {
        }

        public void Work(SomeModel m)
        {

        }
    }
}

当前回答

如果你将T约束为一个类,你就会得到这个错误

其他回答

我不能复制,但我怀疑在你的实际代码中有一个T:类的约束-你需要传播它来让编译器高兴,例如(很难确定没有一个复制的例子):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit

如果你将T约束为一个类,你就会得到这个错误

如果您在泛型类或方法上添加了约束,那么使用它的每个其他泛型类或方法都需要“至少”具有这些约束。