I have a generic method, and wish to create an instance of the type T in question after verifying that it is an array:
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 is the current class, and d_order is a character array defined elsewhere.
The idea is to perform recursion to initialize this. For example, if T is int[][][], and s is the string parameter, I want to create an instance of int[s.Split(d).Length][][] and then fill it with this function called on int[][] and so on.
The above didn't work due to a casting error. I have another attempt below:
replace the array declaration with:
object[] temp = new object[part.Length]
and putting the cast to T after filling in the elements with recursion.
The problem with this is that object[] is not convertible to T so even though I know that every element in the array is of the proper type, I can't convert it to T. If there is a way around that, that would also solve my problem. Thank you for your help.
You can cast temp
to T
like Guru Stron has shown, but that doesn't allow you to use the resulting T
like an array. If you want to use it as an array, you should not cast temp
to T
and keep using temp
instead, because temp
is of type Array
. You can do just about everything you can do on "normal" arrays like int[]
or string[]
on an Array
, except you lose some type safety. But you are using reflection here, so no type safety in the first place.
To set the index i
of temp
to something
, just do:
temp.SetValue(something, i);
You should cast temp
to T
before returning, of course:
return (T)(object)temp;
Here is an example of how you'd write this method with a constant length:
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);
}
}
Try casting temp
to object
first and then to T
:
T tot = (T)(object)temp;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.