2013-02-27 122 views
1

我有MyClass<T> where T : IComparable類,我想實現一個方法,如果TString將被調用。我怎樣才能做到這一點?如何實現類型指定的泛型方法?

現在,我有如下代碼:

public void Method() 
    { 
     ... 

     Type typeParameterType = typeof(T); 
     if (typeParameterType.Equals(typeof(String))) 
     { 
      // here I can't do (String) anyTTypeValue 
      // to call handleString(String) method 
     } 

     ... 
    } 
+0

不知道你爲什麼要這樣做。 'T.ToString()'會有用嗎? – 2013-02-27 08:29:56

+0

是的,這也是一個解決方案! – 2013-02-27 08:40:14

回答

2

嘗試:

(string)(object) anyTypeValue; 

順便說一句,你不必做的一切 - 你可以說:

if(anyTypeValue is string) 
{ 
    string strValue = (string)(object)anyTypeValue; 
    ... 
} 

編輯:

正如@Ilya建議的那樣,在引用類型和Nullable<T>類型的情況下,可以使用as。由於string是引用類型,你可以這樣做:

var strValue = anyTypeValue as string; 
if(strValue != null) 
{ 
    ... 
} 

但是,你不能做同樣的事情與int

var intValue = anyTypeValue as int; //compiler error 

另外請注意,你不能告訴如果strValue != null是假的,因爲anyTypeValuenull開頭,或因爲anyTypeValue不是字符串

在一些使用情況下,這些不是問題,因此使用as將是更可取的。

+0

不會只是99%的時間? – Aron 2013-02-27 08:24:17

+0

不,因爲在調用它之前檢查它是一個字符串。 – 2013-02-27 08:25:43

+0

它的工作原理。這是一個解決方案。但爲什麼我不能'(String)anyTTypeValue'? – 2013-02-27 08:33:34

3

您可以利用as運算符並檢查valString是否不爲空。然後您將可以訪問string特定屬性和方法。下面的代碼片段將顯示主要想法:

public void Method<T>(T val) 
{ 
    string valString = val as string; 
    if(valString != null) 
    { 
     Console.WriteLine (valString.Length); 
    } 
} 

Method("tyto"); //prints 4 
Method(5); //prints nothing 
+0

這就是我正在建議的。使用'as'意味着你不需要投擲對象兩次。 – 2013-02-27 08:29:26

+0

謝謝!這是一個解決方案。但在我的情況下,我寧願@Eren Ersonmez的方式,因爲我必須投它兩次:'temp.value =(T)(Object)BalanceString((String)(Object)temp.value,balanseLength);' – 2013-02-27 08:35:33

+0

您也可以嘗試使用'as as operator'將'temp.value'強制轉換爲'string' – 2013-02-27 08:39:23

相關問題