2012-11-02 75 views
3

動態類型我得到了下面的問題,我的數據流:設置屬性在C#

數據流由一本字典,我想分析和動態指定值的類型。

I.e.我的數據STREA包括:

  • 「日期」, 「2000年1月1日」
  • 「名」, 「喬」
  • 「活着」, 「真」
  • 「健康」, 「100」

現在我想按照這個數據流來設置一個泛型類的我的屬性:

class GenericClass 
{ 
    Hashtable genericAttributes; 
} 

是否有可能通過反射將我的數據流值設置爲正確的類型?

我可以嘗試像:

DateTime.TryParse(date, out myDate); 

的日期時間對象,但是當試圖解析雙打,花車,int16s,int32s,UINT16我不認爲這會工作,...

對此有些想法?

THX和問候

+4

還有'Double.TryParse' ,'Float.TryParse','Short.TryParse'和'Int32.TryParse'等等。 –

+1

你從哪裏得到最終的'Type'? –

+0

是的,我知道,但這會讓我擔心「2.0」可能轉換爲Int16,float和double。 – ffyhlkain

回答

1

我從你的問題的猜測是,他們都是IConvertible,所以我會在下面做一些我的代碼示例。我的想法是,我指定了「想要」順序,即按照我希望類型的順序(如果它們可以適合多種類型),然後嘗試按順序轉換它們。

public class GenericPropClass 
    { 
     public Type type; 
     public object value; 
     public string key; 
    } 

    [TestMethod] 
    public void PropertySet() 
    { 
     var dict = new Dictionary<string, string>(); 
     var resultingList = new List<GenericPropClass>(); 
     // Specify the order with most "specific"/"wanted" type first and string last 
     var order = new Type[] { typeof(DateTime), typeof(int), typeof(double), typeof(string) }; 

     foreach (var key in dict.Keys) 
      foreach (var t in order) 
      { 
       try 
       { 
        var res = new GenericPropClass() 
        { 
         value = Convert.ChangeType(dict[key], t), 
         key = key, 
         type = t, 
        }; 
        resultingList.Add(res); 
        break; 
       } 
       catch (Exception) 
       { 
        // Just continue 
       } 
      } 

    } 

對不起,包含幾乎只有代碼簡短的回答,我可能有時間去改進它,今晚讓我的想法,但是我現在得走了:)

+0

是的!非常感謝@flindeberg。這正是我期待的! – ffyhlkain

+0

@ffyhlkain謝謝;) – flindeberg