在运行时创建通用数组

Nir*_*dar 6 c# generics reflection

在c#中有没有办法做这样的事情:

public void Foo<T>()
{
    T[] arr = Goo() as T[];
}
Run Code Online (Sandbox Code Playgroud)

Goo返回的地方object[],使用反射或其他什么?

Dar*_*rov 6

您可以使用LINQ:

public void Foo<T>()
{
    T[] arr = Goo().OfType<T>().ToArray();
}
Run Code Online (Sandbox Code Playgroud)

在您的示例object[]T[],如果两种类型完全匹配,则您将转换到也将起作用:

public void Foo<T>()
{
    T[] arr = Goo() as T[];
    if (arr != null)
    {
        // use the array
    }
}
Run Code Online (Sandbox Code Playgroud)

例如,这将适用于以下情况:

public object[] Goo()
{
    return new string[] { "a", "b" };
}
Run Code Online (Sandbox Code Playgroud)

然后像这样调用Foo:

Foo<string>();
Run Code Online (Sandbox Code Playgroud)