[英]Win8 (WINRT) C# not allowing Generic Reflection using MakeGenericMethod
[英]C# Reflection, using MakeGenericMethod with method that has the 'new()' type constraint
我正在嘗試使用MethodInfo MakeGenericMethod,如下所示:
foreach (var type in types)
{
object output = null;
var method = typeof (ContentTypeResolver).GetMethod("TryConstruct");
var genmethod = method.MakeGenericMethod(type);
var arr = new object[] { from, output };
if ((bool)genmethod.Invoke(null, arr))
return (IThingy)arr[1];
}
針對以下通用方法:
public static bool TryConstruct<T>(string from, out IThingy result) where T : IThingy, new()
{
var thing = new T();
return thingTryConstructFrom(from, out result);
}
我遇到的問題是我在MakeGenericMethod行上得到了一個爭論異常,因為我傳遞的類型不是'new()'
這有什么辦法? 謝謝
不可以。您只能使用滿足IThingy
和new
約束的類型參數來構造閉合構造的TryConstruct方法。 否則你將擊敗TryConstruct合同:當你調用TryConstruct並且它擊中new T()
線時會發生什么? 不會有一個T()構造函數,所以你已經違反類型安全。
在將其傳遞給MakeGenericMethod之前,您需要檢查該類型是否具有公共默認構造函數。 如果需要使用非默認構造函數實例化類型,則需要創建新方法或TryConstruct重載,可能使用Activator.CreateInstance而不是new T()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.