且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将对象数组转换为泛型类型数组

更新时间:2022-11-20 23:00:08

PLB's answer points out why you don't need to do that, I'll just chime in on why you can't do that.

Let's say you have an object array:

var objectArray = new object[] { 3, 5, 3.3, "test" };

Now how would you say I convert that to a uniform, generic type? There's no guarantee that all of the instances inside the object array will be of the same type, the array might be heterogenous, so this:

public static T[] ConvertTo<T>(object[] arr)
{
    return (T[])arr;
}

var intArray = ConvertTo<int>(objectArray);

Can't really work: Cannot convert type 'object[]' to 'T[]' in the ConvertTo method.

What you can do in such situation is test each and every item if it's of appropriate type, especially since LINQ already has fitting method:

var intArray = objectArray.OfType<int>().ToArray();

Which will give you an array: [3, 5]

So a generic version would be: elementsArray = objectArray.OfType<E>().ToArray();