[英]Given a Type T that satisfies T.isArray, is it possible to initialize a variable of type typeof(T).getElementType?
[英]Is it possible to Create an Array of type typeof(T).getElementOf(), and initialize it within a generic method of <T>?
我有一個通用方法,並希望在驗證它是一個數組后創建一個相關類型 T 的實例:
public static T Ins<T>(string s, int delim) {
if (typeof(T).IsArray) {
char d = d_order[delim];
string[] part = s.Split(d);
Array temp = Array.CreateInstance(typeof(T).GetElementType(), part.Length);
T tot = (T)temp; // doesn't work (can't convert from array to T)
var genMethod = typeof(InputFunctions).GetMethod("Ins").MakeGenericMethod(typeof(T).GetElementType());
//Calling genMethod on substrings of s to create the elements
}
else {
//defining the function for non array types
}
InputFunctions 是當前的 class,d_order 是在別處定義的字符數組。
這個想法是執行遞歸來初始化它。 例如,如果T是int[][][],s是字符串參數,我想創建一個int[s.Split(d).Length][][]的實例,然后用這個function填充調用 int[][] 等等。
由於鑄造錯誤,上述方法無效。 我在下面有另一個嘗試:
將數組聲明替換為:
object[] temp = new object[part.Length]
並在使用遞歸填充元素后將強制轉換為 T 。
這樣做的問題是 object[] 不能轉換為 T,所以即使我知道數組中的每個元素都是正確的類型,我也無法將其轉換為 T。如果有解決方法,那將也解決了我的問題。 謝謝您的幫助。
您可以像 Guru Stron 所示的那樣將temp
轉換為T
,但這不允許您像數組一樣使用生成的T
。 如果要將其用作數組,則不應將temp
轉換為T
並繼續使用temp
,因為temp
是Array
類型。 您幾乎可以在“正常” arrays 上執行您可以執行的所有操作,例如在Array
上執行int[]
或string[]
,除非您失去了一些類型安全性。 但是你在這里使用反射,所以首先沒有類型安全。
要將temp
的索引i
設置為something
,只需執行以下操作:
temp.SetValue(something, i);
當然,您應該在返回之前將temp
轉換為T
:
return (T)(object)temp;
下面是一個示例,說明如何使用恆定長度編寫此方法:
public static T Ins<T>() {
const int length = 10;
if (typeof(T).IsArray) {
Array temp = Array.CreateInstance(typeof(T).GetElementType(), length);
var genMethod = typeof(InputFunctions).GetMethod("Ins").MakeGenericMethod(typeof(T).GetElementType());
for (int i = 0 ; i < length ; i++) {
temp.SetValue(genMethod.Invoke(null, null), i);
}
return (T)(object)temp;
}
else {
return default(T);
}
}
嘗試先將temp
轉換為object
,然后再轉換為T
:
T tot = (T)(object)temp;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.