2012-03-07 183 views
0

這是否可以用任何其他語法?帶泛型類型參數的網絡泛型類型

interface IFoo<T<U>> where U: Bar, new() where T<U>: class, IFoo<T<U>>, new() 

這是一個辦法迫使通用論據IFoo的是一個通用型

class MyFoo<U>: IFoo<MyFoo<U>> where U: Bar, new() 

編輯說明幾點:

  • U是吧...這將成爲客戶實體
  • T is IFoo ...它將成爲客戶業務對象
  • IFoo is interfa行政長官對一些業務對象
  • IFoo的定義List<U> GetList(int compareToCustomerProperty)

編輯說明可用性:

interface IFoo<T<U>> where U: Bar, new() where T<U>: class, IFoo<T<U>>, new() 
    T<U> DoOnce(); 

class MyFoo<U>: IFoo<MyFoo<U>> where U: Bar, new() 
    MyFoo<U> DoOnce(){return this;} 
    MyFoo<U> DoAgain(){return this;}//this is not in interface 

class Test{ 
    public Test(){ 
     IFoo<MyFoo<Bar>> x = new MyFoo<Bar>();//Generics can come as parameters 
     x. 
      DoOnce()//this is from interface 
      DoAgain();//Can access this x's method cause of generic in IFoo 
    } 
} 

我目前可以實現,但我失去了通用U.

可以沒有它? ?共
我會錯過這種方法在我的代碼中的某個點?羅!

我剛來到一個地步,我認爲這將是很好,在我的代碼(方法鏈抽象&混凝土之間,在仿製藥更多的自由)

感謝您的答案!

+0

爲什麼'IFoo'怎麼在意'U'約束?什麼是用例? – 2012-03-07 02:44:27

+0

Hi @ M.Babcock在編輯 – 2012-03-07 03:16:55

+0

的第4點回答瞭解,但不應該'IFoo'將實例化'U'的責任委託給'T '? – 2012-03-07 03:21:17

回答

1

來接近我認爲你正在嘗試做的唯一事情是

public interface IBaz<U> 
{ 
} 

public class Baz<U> : IBaz<U> 
{ 
} 

public interface IFoo<T, U> where T : IBaz<U> where U: Bar, new() 
{ 
}  

public class Foo<U> : IFoo<Baz<U>, U> 
    where U: Bar, new() 
{ 
} 
+0

Hi @ user375487請看IFoo&T之間的關係 – 2012-03-07 03:17:58

+0

是的,我看到了。儘管如此,你寫的幾乎是不可能的。您不能通過引用約束參數來指定約束,也不能實現具有對所聲明類型的引用的接口。 – 2012-03-07 03:43:52

+0

我看到了......謝謝@ user375487 – 2012-03-07 05:19:40

1

不,你不能這樣做,在.NET框架。

看到將泛型類型參數限制爲泛型本身沒有多大意義。考慮以下類型:

public class StringList : List<string> { } 

StringListList<string>是幾乎相同的類型。但是,你能寫

Foo<List<string>> 

,而不是

Foo<StringList> 

List<string>已經從泛型類型定義List<>創建的事實是不是真的有關的大多數使用的,除非你的工作關於某種高度反思的行爲。

我可以比如看到,你可能希望這樣的功能,如果你想要做這樣的事情:

public interface GenericTypeConverter<T> where T : <> 
{ 
    T<V> Convert<U,V>(T<U> thing); 
} 

如果你想創建聲明函數轉換從T<U>T<V>一個轉換器接口,任何通用類型T。但是我只能想象如果你從事複雜的代碼生成/代碼分析。

如果是這種情況,你真正需要的是,你總是可以在運行時檢查類型T是通用的,通過調用typeof(T).IsGenericType

+0

Thanks @ d-b我剛剛寫了一個我正在嘗試做的例子 – 2012-03-07 05:20:30