How to convert object to object[]

前端 未结 4 1706
孤城傲影
孤城傲影 2021-01-17 10:52

I have an object whose value may be one of several array types like int[] or string[], and I want to convert it to a string[]

4条回答
  •  野的像风
    2021-01-17 11:40

    .ToArray makes multiple memory allocations in most cases, but there are few ways around it:

    object value = new[] { 1, 2.3 };
    
    IList list = value as IList;
    string[] strings = new string[list.Count];
    
    for (int i = 0; i < strings.Length; i++)
        strings[i] = Convert.ToString(list[i]);
    

    In most cases that might be a bit overkill and waste of vertical space, so I would use something like the accepted answer with an optional null-conditional operator ? to check if the source is array:

    string[] strings = (value as Array)?.Cast().Select(Convert.ToString).ToArray();
    
        

    提交回复
    热议问题