类型必须是引用类型才能在泛型类型或方法中将其用作参数“T" [英] The type must be a reference type in order to use it as parameter 'T' in the generic type or method
本文介绍了类型必须是引用类型才能在泛型类型或方法中将其用作参数“T"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在深入研究泛型,现在遇到了需要帮助的情况.如主题标题所示,我在下面的派生"类中遇到编译错误.我看到许多其他帖子与此类似,但我没有看到这种关系.有人能告诉我如何解决这个问题吗?
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)
{
}
}
}
推荐答案
我无法重现,但我怀疑在您的实际代码中存在T : class 的约束
- 例如,您需要传播它以使编译器满意(如果没有重现示例就很难确定):
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):
public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
^^^^^
see this bit
这篇关于类型必须是引用类型才能在泛型类型或方法中将其用作参数“T"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文