我正在爲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>
地轉化爲空引用:
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。我目前沒有想法。我有什麼選擇?我能做些什麼來創建這種內部類型?
我不知道我跟着你。你能給個例子嗎? – Steven 2011-03-29 18:51:46
@Akash:感謝這個例子,但是這不幸的是我不能做這個伎倆,因爲我沒有一個通用的'T',只是一個代表'T'的'System.Type'。 – Steven 2011-03-29 19:38:33
T從哪裏來?你不能提供一個工廠代表或其他東西嗎? – 2011-03-29 19:56:25