のタイプT
が実行時(コンパイル時ではない)でしか認識されない場合、ImmutableList<T>
を生成したいと考えています。コンパイル時に不明な型の不変型リストを作成する
Iのようなようなこと作成したい方法
var immutableList = CreateImmutableList(originalList, type);
originalListがIEnumerable
とタイプが生成ImmutableList<T>
ののT
です。
どのように!
(私はNET .Coreで働いている)
編集:私は実用的なソリューションを発見したコメントに感謝します。 AddRangeメソッドを使用します。
namespace Sample.Tests
{
using System;
using System.Collections;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using Xunit;
public class ImmutabilityTests
{
[Fact]
public void CollectionCanBeConvertedToImmutable()
{
var original = new Collection<object>() { 1, 2, 3, 4, };
var result = original.AsImmutable(typeof(int));
Assert.NotEmpty(result);
Assert.IsAssignableFrom<ImmutableList<int>>(result);
}
}
public static class ReflectionExtensions
{
public static IEnumerable AsImmutable(this IEnumerable collection, Type elementType)
{
var immutableType = typeof(ImmutableList<>).MakeGenericType(elementType);
var addRangeMethod = immutableType.GetMethod("AddRange");
var typedCollection = ToTyped(collection, elementType);
var emptyImmutableList = immutableType.GetField("Empty").GetValue(null);
emptyImmutableList = addRangeMethod.Invoke(emptyImmutableList, new[] { typedCollection });
return (IEnumerable)emptyImmutableList;
}
private static object ToTyped(IEnumerable original, Type type)
{
var method = typeof(Enumerable).GetMethod("Cast", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(type);
return method.Invoke(original, new object[] { original });
}
}
}
このwon't作品。コンパイル時に 'Collection'を簡単に作ることができるタイプを知っているか、コンパイラが実行時に何を提供するかを推測することができないタイプを知っていません。 –
HimBromBeere
'CreateImmutableList'は' ImmutableList 'を返すことができないので、'オブジェクト 'を返す必要があります(結局のところ、' T'を知りません)。それはあなたが欲しいものですか?その場合、 'var'がどのような型であるべきかを明示してください。 –
'originalList'も実行時に' IEnumerable 'ですか? –