我有一个方法需要(object value)
并使用一些棘手的规则将其转换为string
。
其中一条规则与值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 :(得分: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);
}
答案 1 :(得分:0)
var e = ((IEnumerable)value).Cast<object>();
此外,字符串连接的Aggregate
非常昂贵 - 您应该使用StringBuilder
或string.Concat
或string.Join
。另外,c.Count() == 0
是多余的。
return string.Concat((IEnumerable)value).Cast<object>().Select(Convert).ToArray())
答案 2 :(得分:0)
只有使用C#4.0的接口和委托中的泛型类型参数支持差异。