2012-03-12 61 views
9

挑戰: 請創建下面的類的實例,(使用任何類型T):不可能的遞歸泛型類定義?

class Foo<T> 
    where T : Foo<T> 
{ 
} 

你可以使用任何你喜歡的技術;簡單的「新MyClass ...」,使用反射,黑客MSIL,無論如何。

+1

瞭解你想達到什麼可能會幫助人們提供更好的替代答案。 – 2012-03-12 07:31:42

+1

[遞歸泛型類型]的可能的重複(http://stackoverflow.com/questions/647533/recursive-generic-types) – Amber 2012-03-12 07:32:29

+3

可能的家庭作業問題? – Carsten 2012-03-12 07:35:24

回答

12
static class Program { 
    static void Main() { 
     Foo<Bar> foo = new Foo<Bar>(); 
    } 
} 
class Foo<T> where T : Foo<T> {} 
class Bar : Foo<Bar> {} 
+0

完美........ – 2012-03-12 08:10:57

+3

或者只是'new Bar()'。 – 2012-03-12 08:40:01

+0

哈哈酷!我其實並不認爲這是可能的!呵呵。我立場糾正。的確很好! :) – 2012-03-12 08:43:16