[英]The type must be a reference type in order to use it as parameter 'T' in the generic type or method
I'm getting deeper into generics and now have a situation I need help with. 我正在深入研究泛型,现在遇到需要帮助的情况。 I get a compile error on the 'Derived' class below as shown in the subject title.
如主题标题所示,我在下面的“派生”类上遇到编译错误。 I see many other posts similar to this one but I'm not seeing the relationship.
我看到许多其他与此类似的帖子,但是我没有看到这种关系。 Can someone tell me how to resolve this?
有人可以告诉我如何解决吗?
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)
{
}
}
}
I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class
- you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example): 我无法复制,但是我怀疑您的实际代码中存在一个
T : class
的约束-例如,您需要传播该约束以使编译器满意(很难说没有复制实例):
public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
^^^^^
see this bit
如果将T
限制为一class
则会出现此错误
如果将约束放在通用类或方法上,则使用它的所有其他通用类或方法都必须“至少”具有这些约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.