0
我在C#(.NET 4.0)中为我的应用程序做了这个方法。 此方法将您作为参数传递给的对象转换为类型T.我想分享它并询问是否有更好的解决方案。以对象作为参数的方法,它返回我想要的类型C#
public static T ReturnMeThis<T>(object variable) {
T dataOut = default(T);
try {
if(Convert.IsDBNull(variable) && typeof(T) == typeof(String))
dataOut = (T)(object)"";
else if(!Convert.IsDBNull(variable))
dataOut = (T)Convert.ChangeType(variable, typeof(T));
return dataOut;
}
catch(InvalidCastException castEx) {
System.Diagnostics.Debug.WriteLine("Invalid cast in ReturnMeThis<" + typeof(T).Name + ">(" + variable.GetType().Name + "): " + castEx.Message);
return dataOut;
}
catch(Exception ex) {
System.Diagnostics.Debug.WriteLine("Error in ReturnMeThis<" + typeof(T).Name + ">(" + variable.GetType().Name + "): " + ex.Message);
return dataOut;
}
}
事情是我所做的方法不能返回null。 – 2011-04-10 04:09:40