2012-03-08 61 views
1

我正在嘗試使用未知類型的AS關鍵字。這裏是我的代碼:如何使用未知類型的AS關鍵字

public GetData(Type MyType, string CSVPath) 
{ 
    var engine = new FileHelperEngine(MyType); 

    try 
    { 
     _Data = engine.ReadFile(CSVPath) as MyType; //error here 
    } 
    catch(Exception ex) 
    { 
     Console.WriteLine("Error occured: " + ex.Message); 
    } 
} 

正如你可以在這段代碼中看到的我得到的錯誤是MyType。有沒有更好的方法來做到這一點

+2

你基本上不能在那裏使用'as'。處理「Type MyType」時,您現在處於元數據和反射的狀態。一旦你開始了那條黑暗的道路,它將永遠支配你的命運。 – 2012-03-08 22:46:42

+0

你有什麼異常? 'as'應該返回null而不是通過例外。 – Jetti 2012-03-08 22:48:14

+0

@Jetti,這裏的錯誤將是*編譯時間*。這不會運行,更不用說返回null。 – 2012-03-08 22:48:47

回答

3

使用通用的方法,而不是在一個Type作爲參數傳遞:

public void GetData<T>(string CSVPath) 
{ 
    var engine = new FileHelperEngine(typeof(T)); 
    _Data = engine.ReadFile(CSVPath) as T; 
    if (_Data != null) 
    { 
     //correct type, do the rest of your stuff here 
    } 
} 
+0

因爲這個類需要是通用的(所以_Data是T類型的)。如果_Data已經是T類型的,你不需要GetData是通用的。 – zmbq 2012-03-08 23:02:54

+0

好的通話,我沒有真正閱讀OP的代碼。我會做一個編輯。 – wsanville 2012-03-08 23:03:30

+0

@zmbq:try塊中有更多的'as'。 – 2012-03-08 23:04:40

1

我不知道我明白。首先,使用as不會引發異常,它只是返回null。第二,我很確定你不想投射,你只是想檢查類型,所以你需要is運營商。但由於MyType僅在運行時才知道,因此確實需要反思。這是很簡單:

object o = engine.Readfile(CSVPath); 
if(MyType.IsAssignableFrom(o.GetType()) 
    _Data = o; 
else 
    Console.WriteLine("Mismatching types: {0} is not of type {1}", o.GetType(), MyType); 

注:我假設_Dataobject型的,否則,你只需要使用as運營商與_Data的類型。

0

這裏有一個類,這樣做,但我有一個很好的例子爲一個動態轉換這樣一個困難時期的思想。 :

using System; 

namespace Test 
{ 
    class Program 
    { 
     private object _data; 

     static void Main(string[] args) 
     { 
      new Program().EntryPoint(); 
     } 

     public void EntryPoint() 
     { 
      GetData(typeof(string), "Test"); 
      Console.WriteLine(_data); 
     } 

     public void GetData(Type myType, string csvPath) 
     { 
      var engine = new FileHelperEngine(myType, csvPath); 

      // This is the line that does it. 
      _data = Convert.ChangeType(engine.ReadFile(csvPath), myType); 
     } 

     private class FileHelperEngine 
     { 
      public string Value { get; set; } 
      public FileHelperEngine(Type t, string value) { Value = value.ToString(); } 

      public string ReadFile(string path) { return Value; } 
     } 
    } 
}