一个包含数组的对象的显式转换 - 转换成数组

6

简单来说-

有没有一种 简单 的方法可以接受一个类型为 object 的变量,其中包含一个 未知数组 实例(UInt16[]、string[]等),并将其视为数组,比如调用 String.Join(",", obj) 生成以逗号分隔的字符串?

微不足道吗?我也这样认为。

考虑以下情况:

object obj = properties.Current.Value;

obj可能包含不同的实例,例如数组,比如UInt16[]、string[]等。

我想将obj视为其类型,即执行对未知类型的转换。完成后,我就能正常继续操作,即:

Type objType = obj.GetType();
string output = String.Join(",", (objType)obj);

当然,上述代码无法运行(objType未知)。以下代码也同样无法运行:
object[] objArr = (object[])obj;   (Unable to cast exception)

仅仅为了明确 - 我并不是试图将对象转换为数组(它已经是一个数组的实例),只是想把它当作一个数组来处理。

谢谢。


1
尝试将对象转换为IEnumerable。 - Artemix
1
也许你可以用 dynamic obj = properties.Current.Value; 替换 object obj = properties.Current.Value;,然后把 obj 当作一个数组来处理? - Guillaume
1个回答

9

假设您正在使用.NET 4或更高版本(其中string.Join获得了更多重载),那么有两个简单的选项:

  • Use dynamic typing to get the compiler to work out the generic type argument:

    dynamic obj = properties.Current.Value;
    string output = string.Join(",", obj);
    
  • Cast to IEnumerable, then use Cast<object> to get an IEnumerable<object>:

    IEnumerable obj = (IEnumerable) properties.Current.Value;
    string output = string.Join(",", obj.Cast<object>());
    

你是我的神!谢谢 :-) - zulfik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接