该类型必须是引用类型,才能在泛型类型或方法使用它作为参数'T' [英] The type must be a reference type in order to use it as parameter 'T' in the generic type or method
问题描述
我越来越深入到仿制药,现在有一个情况我需要帮助。我得到如下图所示的主旨题的派生类的编译错误。我看到类似这样的许多其他职位,但我没有看到的关系。谁能告诉我怎么解决这个问题?
使用系统;
使用System.Collections.Generic;
命名空间示例
{
公共类ViewContext
{
ViewContext(){}
} 公共接口IModel
{
} 公共接口IVIEW< T>其中T:IModel
{
ViewContext ViewContext {搞定;组; }
} 公共类SomeModel:IModel
{
公共SomeModel(){}
公众诠释ID {搞定;组; }
} 公共类基地< T>其中T:IModel
{ 公共库(IVIEW< T>查看)
{
}
} 公共类派生< SomeModel> :基地< SomeModel>其中,SomeModel:IModel
{ 公共派生(IVIEW< SomeModel>查看)
:基地(视图)
{
SomeModel M =(SomeModel)Activator.CreateInstance(typeof运算(SomeModel));
服务与LT; SomeModel> S =新的服务和LT; SomeModel>();
s.Work(米);
}
} 公共类服务与LT; SomeModel>其中,SomeModel:IModel
{
公共服务()
{
} 公共无效工作(SomeModel米)
{ }
}
}
我不能瑞普,但我的犯罪嫌疑人的,在实际code是有约束的地方, T:类
- 你需要的传播,使编译器高兴,例如(很难说肯定没有一个摄制为例):
公共类派生< SomeModel> :基地< SomeModel>其中,SomeModel:类,IModel
^^^^^
看到此位
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):
public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
^^^^^
see this bit
这篇关于该类型必须是引用类型,才能在泛型类型或方法使用它作为参数'T'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!