我知道這是一個老問題,但我覺得批准的答案不是很有幫助。我從來不喜歡必須比較由框架提供的字符串的平等,因爲如果它們在某個時候改變了應用程序的故障。
因此,創建了一些更復雜的系統在運行時構建自己的類型,讓我在此線程中添加20美分。
甲TypeBuilderInstantiation
是ALWAYS的通用類型的表示,即由至少一種TypeBuilder
然後其他實例的Type
(RuntimeType
,TypeBuilder
和/或TypeBuilderInstantiation
)的。這意味着所討論類型的泛型類型定義是TypeBuilder
或至少一個泛型參數是TypeBuilder
,GenericTypeParameterBuilder
或它自己的TypeBuilderInstantiation
。 (在GenericTypeParameterBuilder
情況下,如果它是由泛型類型本身聲明,它不計數。)
下面是一個例子如何獲得的TypeBuilderInstantiation
實例:
AssemblyName myAssemblyName = new AssemblyName("MyAssembly");
AssemblyBuilder myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder myModule = myAssembly.DefineDynamicModule("MyModule");
TypeBuilder myType = myModule.DefineType("MyType");
//myType (MyType) is TypeBuilder
Type collectionType = typeof(Collection<>).MakeGenericType(myType);
//collectionType (Collection<MyType>) is TypeBuilderInstantiation
TypeBuilder myGenericType = myModule.DefineType("MyGenericType");
GenericTypeParameterBuilder myGenericParam = myGenericType.DefineGenericParameters("T")[0];
//myGenericType (MyGenericType<T>) is TypeBuilder
Type genericType = myType.MakeGenericType(typeof(string));
//genericType (MyGenericType<string>) is TypeBuilderInstantiation
TypeBuilder myOtherGenericType = myModule.DefineType("MyOtherGenericType");
GenericTypeParameterBuilder myOtherGenericParam = myOtherGenericType.DefineGenericParameters("S")[0];
Type otherGenericType = myType.MakeGenericType(myOtherGenericParam);
//otherGenericType (MyGenericType<S>) is TypeBuilderInstantiation
這裏有一個漂亮的小實施,檢查是否類型是否爲TypeBuilderInstantiation
。
public static bool IsTypeBuilderInstantiation(Type type)
{
bool isTypeBuilderInstantiation = false;
if (type.IsGenericType && !(type is TypeBuilder))
{
foreach (var genericTypeArg in type.GetGenericArguments())
{
if (isTypeBuilderInstantiation = (
genericTypeArg is TypeBuilder ||
genericTypeArg is GenericTypeParameterBuilder ||
IsTypeBuilderInstantiation(genericTypeArg)))
break;
}
isTypeBuilderInstantiation |= type.GetGenericTypeDefinition() is TypeBuilder;
}
return isTypeBuilderInstantiation;
}
你如何獲得該實例?如果沒有創建,TypeBuilder.GetMethods也會拋出一個異常。你想做什麼? – leppie 2011-01-19 14:14:57