我在这里处理泛型,但我有一个奇怪的情况,我试图将一个类的实例分配给一个泛型属性。
class Context<A,T> where A: Answer<T>
{
void SomeMethod()
{
A answer; // suppose it have a value;
answer.context=this; // produce CS00029 error
}
}
class Answer<T>
{
Context<Answer<T>,T> context {get;set;}
}
对于感兴趣的人,我从本网站以外的人那里找到了解决方案,这就是他的建议:
public class Context<A, T>: IContext<A, T> where A : Answer<T>
{
void SomeMethod()
{
A answer = Activator.CreateInstance<A>();
answer.context = this;
}
}
public class Answer<T>
{
public IContext<Answer<T>, T> context { get; set; }
}
public interface IContext<out A, T> {}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句