在运行时创建一个通用的阵列 [英] Creating a generic array at runtime
本文介绍了在运行时创建一个通用的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有在C#的方式做这样的事情:
<预类=郎-CS prettyprint-覆盖>
公共无效美孚< T>()
{
T [] = ARR粘粘()为T [];
}
在哪里咕返回 [对象] $ ?C $ C>,使用反射或任何
解决方案
您可以使用LINQ:
公共无效美孚< T>()
{
T [] ARR =粘粘()OfType< T>()ToArray的() ;
}
在您的例子中,你正在铸造 [对象]
到 T []
如果两种完全匹配这也将工作:
公共无效美孚< T>()
{
T [] = ARR粘粘()为T [];
如果(ARR!= NULL)
{
//使用数组
}
}
例如,这将在以下情况下工作:
公共对象[]粘粘()
{
返回新的字符串[] {A,b};
}
,然后调用美孚这样的:
美孚<串GT;();
Is there a way in c# to do something like this:
public void Foo<T>()
{
T[] arr = Goo() as T[];
}
Where Goo returns an object[]
, Using reflection or whatever?
解决方案
You could use LINQ:
public void Foo<T>()
{
T[] arr = Goo().OfType<T>().ToArray();
}
In your example you are casting the object[]
to T[]
which will also work if the two types match exactly:
public void Foo<T>()
{
T[] arr = Goo() as T[];
if (arr != null)
{
// use the array
}
}
For example this will work in the following case:
public object[] Goo()
{
return new string[] { "a", "b" };
}
and then calling Foo like this:
Foo<string>();
这篇关于在运行时创建一个通用的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文