view plaincopy to clipboardprint?
return
control as T;
return
control as T;
而函數二當中則使用了
view plaincopy to clipboardprint?
return (
T)Enum.Parse(type, key, true);
return (
T)Enum.Parse(type, key, true);
那么能不能使用
view plaincopy to clipboardprint?
return Enum.Parse(type, key, true) as
T;
return Enum.Parse(type, key, true) as
T;

答案是否定的。原因Debugger會告訴你,因為T可能是值類型也有可能是引用類型。而as只能用在引用類型上。

那為什么函數一可以呢?是因為在聲明函數的時候
view plaincopy to clipboardprint?
public static
T FindControl<T>(Control root, string id) where T : Control
public static
T FindControl<T>(Control root, string id) where T : Control

這里指定了where T : Control,就是說T一定是Control的子類,因此T一定是引用類型,所以可以使用as T

都說到這里了,順便說說泛型where的用法。

where是用在泛型中對類型的限制上。要對T做出具體的限制就要使用where

where T : struct : 表示T的繼承鏈中必須包含System.ValueType這個類型
where
T : class : 表示T的繼承鏈中必須不包含System.ValueType這個類型
where
T : new() : 表示T這個類型必須包含有默認的構造函數
where
T : NameOfBaseClass : 表示必須繼承自這個類
where
T : NameOfInterFace : 表示必須實現這個接口
上面對T : struct和對T : class的解釋有些拗口,這個問題牽扯到structclass是否能互相繼承的問題。也就是說,structclass到底有什么不同呢?且聽下回分解……

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 AndrewHsiao 的頭像
    AndrewHsiao

    Andrew的部落格

    AndrewHsiao 發表在 痞客邦 留言(0) 人氣()