显式转换包含数组的对象 - 到数组

zul*_*fik 6 c# arrays casting object implicit

短版 -

是否有一种简单的方法来获取包含未知数组实例的类型对象的变量(UInt16 [],string []等)并将其视为数组,比如调用String.Join(",",obj)生成逗号分隔的字符串?

不重要的?我也是这么想的.

考虑以下:

object obj = properties.Current.Value;
Run Code Online (Sandbox Code Playgroud)

obj可能包含不同的实例 - 例如一个数组,比如UInt16 [],string []等.

我想将obj视为它的类型,即 - 执行转换为未知类型.完成后,我将能够正常继续,即:

Type objType = obj.GetType();
string output = String.Join(",", (objType)obj);
Run Code Online (Sandbox Code Playgroud)

当然,上面的代码不起作用(objType unknown).

这也不是:

object[] objArr = (object[])obj;   (Unable to cast exception)
Run Code Online (Sandbox Code Playgroud)

只是要清楚 - 我不是试图将对象转换为数组(它已经是数组的实例),只是能够将其视为一个.

谢谢.

Jon*_*eet 9

假设您正在使用.NET 4(string.Join获得更多重载)或以后有两个简单的选项:

  • 使用动态类型来使编译器计算泛型类型参数:

    dynamic obj = properties.Current.Value;
    string output = string.Join(",", obj);
    
    Run Code Online (Sandbox Code Playgroud)
  • 演员IEnumerable,然后Cast<object>用来获得IEnumerable<object>:

    IEnumerable obj = (IEnumerable) properties.Current.Value;
    string output = string.Join(",", obj.Cast<object>());
    
    Run Code Online (Sandbox Code Playgroud)