簡體   English   中英

泛型 - 使用父類指定泛型中的類型

[英]Generics - Using parent class to specify type in generics

我正在研究一些協方差/逆變問題,我有一個更廣泛的問題,但這一切歸結為:

GenericRepository<BaseEntity> repo = new GenericRepository<ProductStyle>(context);

這不起作用,即使BaseEntity是ProductStyle的父抽象類,有沒有辦法實現這一點?

這樣做的唯一方法是在interface (不是class )上使用out通用限制(這將使得很難保存對象,但很難檢索它們)。 如果你有:

interface IGenericRepository<out T> {...}

然后可以將IGenericRepository<ProductStyle>分配給IGenericRepository<BaseEntity>類型的變量,因為所有ProductStyle也是BaseEntity ,並且我們限制自己使用協變/ out

IGenericRepository<BaseEntity> tmp = GetRepo<ProductStyle>(context);
// note that the right-hand-side returns IGenericRepository<ProductStyle>
...
private IGenericRepository<T> GetRepo(...) {...}

但請注意,這種協變/ out使用使得無法執行以下操作:

interface IGenericRepository<out T>
{
    T Get(int id); // this is fine, but:
    void Save(T value); // does not compile; this is not covariantly valid
}

我只是想知道這樣的事情是否也會有用 - 使用對GenericRepository定義的限制來限制T可以是的基類型:

void Main()
{
    var repo = new GenericRepository<ProductStyle>(new ProductStyle());
    Console.WriteLine(repo.ToString());  //just output something to make sure it works...
}

// Define other methods and classes here
public class GenericRepository<T> where T : BaseEntity {
    private readonly T _inst;

    public GenericRepository(T inst){
        _inst = inst;
        _inst.DoSomething();
    }
}

public class BaseEntity {
    public Int32 Id {get;set;}

    public virtual void DoSomething() { Console.WriteLine("Hello"); }
}

public class ProductStyle : BaseEntity {
}

因此,如果您有一個GetRepo<T>方法,該方法可以返回T的GenericRepository,並且您確信TBaseEntity的子級。

暫無
暫無

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

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