Silverlight 用の再利用可能なライブラリを作成しています。System.Type
ライブラリには内部ジェネリック型が含まれており、このジェネリック型の新しいインスタンスを作成する必要がありますが、ある時点でジェネリック型引数を使用できず、ジェネリック引数を表すオブジェクトしかありません。リフレクションを使用してインスタンスを作成しようとしましたが、このクラスは内部クラスであり、Silverlight は実質的に部分信頼で実行されるため、これは失敗します。
これが私がこれまでに試したことです:
private INonGenericInterface CreateInstance(Type type)
{
// Activator.CreateInstance fails
var instance = Activator.CreateInstance(
typeof(InternalGenericType<>).MakeGenericType(type));
// Invoking the default constructor of that type fails.
var producer = typeof(InternalGenericType<>)
.MakeGenericType(type)
.GetConstructor(new Type[0])
.Invoke(null);
return (INonGenericInterface)producer;
}
これは私の内部タイプです。派手なものはありません:
internal class InternalGenericType<T> : INonGenericInterface
where T : class
{
public InternalGenericType()
{
}
}
Nullable<T>
内部型を生成できるファクトリを作成するために、構造体をファクトリとして悪用することさえ試みました。ただし、デフォルトでNullable<T>
は null 参照に変換されます。
internal static class InternalGenericTypeFactory
{
public static INonGenericInterface Create(Type serviceType)
{
var nullType = typeof(Nullable<>).MakeGenericType(
typeof(Factory<>).MakeGenericType(serviceType));
// Activator succesfully creates the instance, but .NET
// automatically converts default Nullable<T>s to null.
object nullInstance = Activator.CreateInstance(nullType);
var getValueMethod =
nullType.GetMethod("GetValueOrDefault", new Type[0]);
// Invoke fails, because nullInstance is a null ref.
var factory = getValueMethod.Invoke(nullInstance, null);
return ((IFactory)factory).CreateInstance();
}
internal interface IFactory
{
INonGenericInterface CreateInstance();
}
internal struct Factory<T> : IFactory where T : class
{
public INonGenericInterface CreateInstance()
{
return new InternalGenericType<T>();
}
}
}
ご想像のとおり、API を汚染するため、この型を公開したくありません。私は現在アイデアがありません。私のオプションは何ですか?この内部型を作成するにはどうすればよいですか?