簡體   English   中英

C#。 是否可以使用具有基類型約束的靜態泛型類,該基類型約束具有帶有進一步基類型約束的方法

[英]C#. Is is possible to have a static generic class with a base type constraint that has a method with a further base type constraint

我希望能夠創建一個基類型約束的靜態泛型類型

public static class Manager<T> where T : HasId
{
    public static T GetSingleById(ref List<T> items, Guid id)
    {
        // the Id is a property provided by HasId
        return (from i in items where i.Id == id select i).SingleOrDefault();
    }
}

然后添加另一種方法

...
    public static IEnumerable<T> GetManyByParentId(ref List<T> items, Guid parentId) where T : HasIdAndParentId
    {
        // the parentId is a property of HasIdAndParentId which subclasses HasId
        return from i in items where i.ParentId == parentId select i;
    }
...

由於HasIdAndParentId子類HasId滿足約束條件T:HasId但編譯器不接受方法的where基類型約束。

有任何想法嗎?

在這種情況下,您沒有在方法上重新定義類型參數,因此您無法應用任何新約束。 你應該能夠這樣做:

public static IEnumerable<T2> GetManyByParentId<T2>(
    ref List<T2> items, Guid parentId) 
    where T2 : T, HasIdAndParentId { .. } 

使GetManyByParentId方法本身是通用的,並將其通用參數綁定到T

public static IEnumerable<R> GetManyByParentId<R>(
                                    ref List<R> items, Guid parentId) 
       where R : T, HasIdAndParentId 

Ben M的代碼示例將不會編譯,除非HasIdAndParentId是一個接口類型,它不是,由名稱判斷。

使第二個方法本身具有通用性並使其依賴於自己的類型參數(與T不同)將為您提供所需的約束。

public static IEnumerable<T1> GetManyByParentId<T1>(ref List<T1> items, Guid parentId) where T1 : HasIdAndParentId
{
    // the parentId is a property of HasIdAndParentId which subclasses HasId
    return from i in items where i.ParentId == parentId select i;
}

暫無
暫無

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

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