簡體   English   中英

是否可以將泛型類型約束到Interface,new()?

[英]Is it possible to constrain generic types to Interface, new()?

我正在嘗試創建一個簡單的對象回收類

public class ObjectPool<T> where T : class, IRecyclable, new()
{
}

我希望能夠在我的界面中使用它:

public interface ISomeInterface : IRecyclable
{
}

ObjectPool<ISomeInterface> pool = new ObjectPool<ISomeInterface>();

但這會產生錯誤:

error CS0310: The type `ISomeInterface' must have a public parameterless constructor in order to use it as parameter `T' in the generic type or method `ObjectPool<T>'

根據我在線閱讀的內容,我知道我無法在界面中指定構造函數。

我已經讀過你可以使用反射代替“new”來創建一個新實例,盡管我擔心執行這個實例化的速度。

解決這種情況的正確方法是什么? 有一個更簡單的解決方案,我完全忽略了嗎?

您無法在那里提供界面。 classnew要求它是可構造的引用類型。

接口只能實現其他接口。

interface IA : IB, IC
{
    ...
}

解決困境的一個好方法是引入工廠界面。

interface IThing
{
    ...
}

interface IThingFactory
{
    IThing Create();
}

現在,任何想要有能力創建東西的東西都應該為此目的獲得一個IThingFactory

如果您需要工廠的通用概念,可以使用以下內容:

interface IFactory<T>
{
    T Create();
}

class ObjectPool<T, F>
    where T : IRecyclable        
    where F : IFactory<T>
{
    public ObjectPool(F factory)
    {
        ...
    }
}

您無法構造ObjectPool<ISomeInterface> 你可以有一個泛型類型MyClass<TT> where T:class,ISomeInterface,new()聲明一個ObjectPool<TT> ,然后在聲明MyClass<SomeClassWhichImplementsISomeInterfaceAndHasADefaultConstructor>類型的變量,但編譯器只能執行方法ObjectPool<T>T是滿足所有約束的特定已知類類型時

或者,您可以省略new約束,然后要求構造ObjectPool<T>任何代碼必須將構造函數(或創建實例的其他方法)傳遞給Func<T> 這樣就可以創建一個ObjectPool<ISomeInterface>前提是有一個方法,當被調用時,它將返回一個實現ISomeInterface的某種合適類型的新對象。

暫無
暫無

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

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