簡體   English   中英

如何為通用屬性分配參考值

[英]How to assign a reference value to a generic property

我在這里處理泛型,但是遇到這種奇怪的情況,我試圖將類的實例分配給泛型屬性。

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

解決方案鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM