简体   繁体   English

是否可以创建 typeof(T).getElementOf() 类型的数组,并在通用方法中对其进行初始化<t> ?</t>

[英]Is it possible to Create an Array of type typeof(T).getElementOf(), and initialize it within a generic method of <T>?

I have a generic method, and wish to create an instance of the type T in question after verifying that it is an array:我有一个通用方法,并希望在验证它是一个数组后创建一个相关类型 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 is the current class, and d_order is a character array defined elsewhere. InputFunctions 是当前的 class,d_order 是在别处定义的字符数组。

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.例如,如果T是int[][][],s是字符串参数,我想创建一个int[s.Split(d).Length][][]的实例,然后用这个function填充调用 int[][] 等等。

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.并在使用递归填充元素后将强制转换为 T 。

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.这样做的问题是 object[] 不能转换为 T,所以即使我知道数组中的每个元素都是正确的类型,我也无法将其转换为 T。如果有解决方法,那将也解决了我的问题。 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.您可以像 Guru Stron 所示的那样将temp转换为T ,但这不允许您像数组一样使用生成的T 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 .如果要将其用作数组,则不应将temp转换为T并继续使用temp ,因为tempArray类型。 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.您几乎可以在“正常” arrays 上执行您可以执行的所有操作,例如在Array上执行int[]string[] ,除非您失去了一些类型安全性。 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的索引i设置为something ,只需执行以下操作:

temp.SetValue(something, i);

You should cast temp to T before returning, of course:当然,您应该在返回之前将temp转换为T

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 :尝试先将temp转换为object ,然后再转换为T

T tot = (T)(object)temp;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 给定一个满足 T.isArray 的类型 T,是否可以初始化一个 typeof(T).getElementType 类型的变量? - Given a Type T that satisfies T.isArray, is it possible to initialize a variable of type typeof(T).getElementType? 通用嵌套类型中的typeof(T) - typeof(T) within generic nested types C#通用T类TypeOf,这可能吗? - C# Generic T Class TypeOf, is this possible? 简单泛型-这可能吗 <typeof(T)> ()? - Simple Generics — Is this possible Method<typeof(T)>()? 在运行时将对象数组转换为T类型的通用数组typeof - Conversion of object array to Generic array typeof T Type at runtime C# 泛型乐趣:哪里有类型(列表 <T> )!= typeof(列表 <T> ),并使用Reflection获取通用参数的泛型方法 - Generics Fun: Where typeof(List<T>) != typeof(List<T>), and using Reflection to get a generic method, with generic parameters 为什么VS警告我typeof(T)在类型参数被限制为实现T的泛型方法中永远不是提供的类型? - Why does VS warn me that typeof(T) is never the provided type in a generic method where the type parameter is restricted to implement T? 如何初始化泛型参数类型 T? - How to initialize generic parameter type T? 将typeof(x)类型传递给泛型方法 - Pass typeof(x) type to generic method 是否可以创建通用的Func <T> <T> - Is it possible to create a generic Func<T><T>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM