如何为通用属性分配参考值

时间:2019-05-28 23:37:42

标签: c# generics

我在这里处理泛型,但是在这种奇怪的情况下,我试图将类的实例分配给泛型属性。

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;}
}

1 个答案:

答案 0 :(得分:0)

对感兴趣的人,我从该网站之外的某个人那里找到了解决方案,这是他的建议:

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> {}