[英]Generic cast method returning base type (struct)
我想編寫一個方法,將值(對象)轉換為基本類型(如string,int,double等)。 我在一個在對象上映射DataRows的例程中使用此方法。
我寫了這個:
public static T CastObjectToBasicType<T>(DataRow row, string column)
where T : struct
{
object cellValue = row[column];
if (typeof(T) == typeof(string))
return ToString(cellValue);
if (typeof(T) == typeof(int) || typeof(T) == typeof(int?))
return ToInt(cellValue);
if (typeof(T) == typeof(bool) || typeof(T) == typeof(bool?))
return ToBool(cellValue);
if (typeof(T) == typeof(double) || typeof(T) == typeof(double?))
return ToDouble(cellValue);
if (typeof(T) == typeof(decimal) || typeof(T) == typeof(decimal?))
return ToDecimal(cellValue);
if (typeof(T) == typeof(DateTime) || typeof(T) == typeof(DateTime?))
return ToDateTime(cellValue) ;
throw new ArgumentException("T not supported");
}
其中ToString,ToBool,ToDouble等方法是將輸入轉換為desidered類型的簡單方法。
上面的代碼沒有編譯; 問題是我無法將結果轉換為類型T,因為T是一個結構而且我無法使用(用於exaple)
return ToDouble(obj) as T;
也不
return (T) ToDouble(obj);
如果我替換該條款
where T : struct
同
where T : class
然后我無法使用int,bool,double等調用方法...作為T因為它們不是類。
我不知道是否有辦法實現這一目標; 另一種方法是直接調用ToBool,ToInt等簡單方法,而不是從泛型方法中傳遞,但我更喜歡使用單個強制轉換方法。
有什么我能做的嗎? 任何幫助將不勝感激,也是替代品。
提前致謝。
這是因為,就編譯器所知, T
和例如DateTime
之間沒有可能的轉換。
嘗試將DateTime
上傳到唯一的祖先DateTime
和T
有共同點 - object
- 然后向下轉換回T
return (T) (object) ToDouble(obj);
除非你真的想限制某些東西(接口,類,結構等),否則你不需要指定where T子句。 在這里你沒有,所以只需刪除where子句
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.