2011-09-01 56 views
0

我有一個方法需要(object value)並將其轉換爲string並帶有一些棘手的規則。IEnumerable <object>來自IEnumrable的對象<T>

其中一個規則與值爲IEnumerable時有關。在這種情況下,我需要在枚舉處理每個文件:

public string Convert(object value) 
{ 
    var valuetype = value.GetType(); 
    if (valuetype.GetInterface("IList") != null) 
    { 
     var e = (IEnumerable<object>) value; 
     return e.Count() == 0 ? 
      "" : 
      e.Select(o=>Convert(o)).Aggregate("", (c, s) => c+s); 
    } 
} 

當然,如果值是List<string>,例如,線

var e = (IEnumerable<object>) value;

拋出異常

Unable to cast object of type 'System.Collections.Generic.List`1[System.String]' to type 'System.Collections.Generic.IEnumerable`1[System.Object]'.

任何想法,我怎麼能擺脫它?

+0

你是指集合中的每個項目? – msarchet

+0

你剛加入字符串到一起嗎? –

+0

您使用的是.net版本比4更舊? – CodesInChaos

回答

1

喜歡的東西

var e = ((IEnumerable) value).Cast<object>()

不過,我想,這可能符合這一要求:

public static string Convert(object value) 
    { 
     if (value is string) 
      return value.ToString(); 

     var data = value as IEnumerable; 
     if (data == null) 
      return string.Empty; // I think you missed this one 

     var e = data.Cast<object>(); 
     return e.Count() == 0 ? 
       string.Empty : 
       e.Select(o => Convert(o)).Aggregate("", (c, s) => c + s); 

    } 
+0

不幸的是,'valuetype.GetInterface(「IEnumerable」)!!= null' for'string'太 – dmay

+0

當然,剛剛測試過它:編輯。 –

+0

好,'(值爲IEnumerable).Cast ()'做了詭計。 – dmay

0
var e = ((IEnumerable)value).Cast<object>(); 

此外,Aggregate字符串連接實在是昂貴的 - 你應該使用StringBuilderstring.Concatstring.Join代替。另外,c.Count() == 0是多餘的。

return string.Concat((IEnumerable)value).Cast<object>().Select(Convert).ToArray()) 
+0

問題是值可以是'IEnumerable '或''或其他什麼 – dmay

0

方差僅在接口和委託泛型參數與C#4.0的支持。

相關問題