[英]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.