2012-06-25 30 views
2

誰能告訴我差T獲取<T>(INT ID)和T獲取(INT ID)

public T Get<T>(int id) 

public T Get(int id) 
+0

指示哪個是在運行時定義的一般類型參數。這個類型在類實例化時指定(你的第二行需要在對象創建時定義T)或者調用方法(第一行代碼)。 – davenewza

+0

@davenewza:您的評論是正確的兩種情況下,實際上是通用的螞蟻仿製藥。像「這裏T是什麼意思?」或「什麼是泛型?」 ;) – abatishchev

回答

6

之間的差異比較:

class First 
{ 
    public T Get<T>(int id) // T is declared in the method scope 
    { 
    } 
} 

class Second<T> 
{ 
    public T Get(int id) // T is declared in the class scope 
    { 
    } 
} 

也有一個第三方案:

class Third<U> 
{ 
    public T Get<T>(int id) // T is declared in the method scope when class scope has another generic argument declared 
    { 
    } 
} 
+1

+1,讓我補充一點,這兩種情況之間的混淆是導致如下問題的原因:http://stackoverflow.com/questions/6740978/type-parameter-t-has-the-same-name -as-the-type-parameter-from-outer-type –

+1

不要忘記存在稱爲'T'的類型的情況(不要這樣做!) –

0

閱讀Generics之前,你可以在代碼中使用它們。

3

不同之處在於,如果這是在T之前尚未定義的情況下,則使用第一種類型的聲明。即。

public class MyClass 
{ 
    public T Get<T>(int id); 
} 

而第二當T已經在類級定義的。即。

public class MyClass<T> 
{ 
    public T Get(int id); 
} 

在這種情況下,您也可以使用第一種類型的聲明 - 這是有效的速記。效果沒有區別。

編輯事實上,第二個聲明只要求T是在範圍,另一個例子是一個嵌套類如...

public class MyClass<T> 
{ 
    public class NestedClass 
    { 
    public T Get(int i); 
    } 
}