2009-07-24 10 views
9

Dlaczego mogę to zrobić:Dlaczego "as T" otrzymuje błąd, ale rzutowanie z (T) nie powoduje błędu?

public T GetMainContentItem<T>(string moduleKey, string itemKey) 
{ 
    return (T)GetMainContentItem(moduleKey, itemKey); 
} 

ale nie w ten sposób:

public T GetMainContentItem<T>(string moduleKey, string itemKey) 
{ 
    return GetMainContentItem(moduleKey, itemKey) as T; 
} 

Zarzuca, że ​​nie ogranicza typ rodzajowy mało, ale myślę, że zasada ta stosuje się do odlewania również z "(T)".

Odpowiedz

23

Ponieważ "T" może być wartością typu, a "jak T" nie ma sensu dla typów wartości. Możesz to zrobić:

public T GetMainContentItem<T>(string moduleKey, string itemKey) 
    where T : class 
{ 
    return GetMainContentItem(moduleKey, itemKey) as T; 
} 
+0

Twoja odpowiedź jest niepoprawna, możesz rzutować na typy wartości, wynik będzie zerowy, zobacz ten post i odpowiedź Jona Skeeta: http://stackoverflow.com/questions/496096/casting-vs-using-the -as-keyword-in-the-clr – Mikhail

6

Jeśli T jest typem wartości, jest to wyjątek, należy upewnić się, że T jest typu Nullable lub klasy.

1

Czy T jest typem wartości? Jeśli tak, to jeśli operator as ulegnie awarii, zwróci null, którego nie można zapisać w typie wartości.

0

Rozszerzenie na Jurij Faktorovichs odpowiedź:

public T GetMainContentItem<T>(string moduleKey, string itemKey) where T: class 
{ 
    return GetMainContentItem(moduleKey, itemKey) as T; 
} 

będzie to rade ...

0

Ponieważ as T pobiera null w przypadku, że nie może rzutować na T w przeciwieństwie do (T) że zgłasza wyjątek. Więc jeśli T nie jest Nullable lub class nie może być null ... myślę.

Powiązane problemy