我有一个 List 类型的集合,我想将其转换为 SomeType[]。 SomeType 在运行前未知。

这必须通过以下程序的签名来完成。

private object ConvertListToArray(IList  collection)
{
       // This does not work since SomeType is not known before runtime.
       var convertedList = collection.Cast<SomeType>().ToArray();
        return convertedList;
}

注意collection是IList,但是知 Prop 体类型是
     List<SomeType>

返回集合必须是 SomeType[] 类型的对象。

如何才能做到这一点?

最佳答案

public static class ListExtensions
{
    public static T[] ConvertToArray<T>(IList list)
    {
        return list.Cast<T>().ToArray();
    }

    public static object[] ConvertToArrayRuntime(IList list, Type elementType)
    {
        var convertMethod = typeof(ListExtensions).GetMethod("ConvertToArray", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(IList)}, null);
        var genericMethod = convertMethod.MakeGenericMethod(elementType);
        return (object[])genericMethod.Invoke(null, new object[] {list});
    }

}
[TestFixture]
public class ExtensionTest
{
    [Test]
    public void TestThing()
    {
        IList list = new List<string>();
        list.Add("hello");
        list.Add("world");

        var myArray = ListExtensions.ConvertToArrayRuntime(list, typeof (string));
        Assert.IsTrue(myArray is string[]);
    }
}

关于c# - 将 IList 转换为 SomeType[],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12313672/

10-15 22:43