2011-04-08 78 views
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; 
      } 
     } 

回答

0

Just cast the object?

TypeIWant t = variable as TypeIWant; 

if(t != null) 
{ 
// Use t 
} 

我错过了什么吗?

0

正如tomasmcguinness所说,as关键字可以正常工作。它会在无效转换时返回null,而不会抛出错误。如果你想有一个记录无效转换的专用方法,你可以这样做:

public static T ReturnMeThis<T>(object variable) where T : class 
{ 
    T dataOut = variable as T; 
    if (dataOut == null) 
     System.Diagnostics.Debug.WriteLine(String.Format("Cannot cast {0} as a {1}", variable.GetType().Name, dataOut.GetType().Name)); 

    return dataOut; 
} 
+0

事情是我所做的方法不能返回null。 – 2011-04-10 04:09:40

相关问题