我正在更深入地研究泛型,现在遇到需要帮助的情况。我在下面的“派生”类上收到编译错误,如主题标题所示。我看到许多其他类似的帖子,但我没有看到这种关系。有人可以告诉我如何解决这个问题吗?
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 : class
某处的约束 - 例如,您需要传播它以使编译器满意(很难确定没有复制示例):
public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
^^^^^
see this bit
如果您将 T
限制为 class
,则会收到此错误
如果您对泛型类或方法施加约束,则使用它的每个其他泛型类或方法都需要“至少”具有这些约束。