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的解釋有些拗口,這個問題牽扯到struct和class是否能互相繼承的問題。也就是說,struct和class到底有什么不同呢?且聽下回分解……