C#:将 T 转换为 T[]

标签 c# .net generics casting

如果它是数组,我想将 T 转换为 T[]。

static T GenericFunction<T>(T t)
{
       if (t == null) return default(T);

       if (t.GetType().IsArray)
       {
            //if object is an array it should be handled
            //by an array method
            return (T) GenericArrayFunction((T[])t); 
       }
       ...
}

static T[] GenericArrayFunction<T>(T[] t)
{
       if (t == null) return default(T);

       for (int i = 0 ; i < t.Length ; i++) 
       {
            //for each element in array carry
            //out Generic Function
            if (t[i].GetType().IsArray())
            {
                 newList[i] = GenericArrayFunction((T[])t[i]); 
            }
            else
            {
                 newList[i] = GenericFunction(t[i]);
            }
       }
       ...
}

错误 如果我尝试 (T[])t

Cannot convert type 'T' to 'T[]'

错误 如果我只是尝试通过 t

The type arguments for method 'GenericArrayFunction(T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly.

最佳答案

从你的具体例子来看,你能不能定义两个方法,让编译器在传入数组时选择正确的方法?

using System;

class Program
{
    static T GenericFunction<T>(T t)
    {
        Console.WriteLine("GenericFunction<T>(T)");
        return default(T);
    }

    static T[] GenericFunction<T>(T[] t)
    {
        // Call the non-array function
        for(int i = 0; i < t.Length; ++i)
            t[i] = GenericFunction(t[i]);

        Console.WriteLine("GenericFunction<T>(T[])");
        return new T[4];
    }

    static void Main()
    {
        int[] arr = {1,2,3};
        int i = 42;

        GenericFunction(i);   // Calls non-array version
        GenericFunction(arr); // Calls array version
    }
}

关于C#:将 T 转换为 T[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3653209/

相关文章:

c# - ASP.Net Core 使用什么依赖注入(inject)框架?

c# - 如何: Create a Key In the Registry (Visual C#)?

asp.net - 发布管理 - 发布给用户子集 - 它对于面向公众的网站将如何工作

c# - IDisposable、Finalizers 和非托管资源的定义

java - 将泛型与 Firebase snapshot.getValue() 结合使用的最佳实践

c# - 委托(delegate)给 C# 中的属性

c# - 如何在 cshtml(razor)上设置属性?

c# - 如何找出最快的算法

c# - C# 中的大型数组算术

c# - ICollection<string> 到 string[]