c#对象数组到int数组 [英] c# object array to int array

查看:71
本文介绍了c#对象数组到int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



i有一个简单的问题:

我可以显式地将一个对象数组转换为一个int数组吗?



可能不是因为对象数组可以包含浮点数或长数等等。

:doh:

谢谢

dj4400

Hi,
i have a simple question:
can i explicitly cast an object array to an int array?

probably not because the object array can contain floats or longs etc..
:doh:
thanks
dj4400

推荐答案

查看 ConvertAll 。这允许您指定执行转换的函数。由于您指示数组可能包含非整数数据类型(例如float),因此您需要执行显式强制转换以截断值。
Look at ConvertAll. That allows you to specify a function to perform the conversion. Since you indicated the array may contain non-integer data types (such as float), you will need to perform an explicit cast to truncate the values.


您无法转换整数数组到一个对象数组。但你可以做到以下几点:



You can't convert an integer array into an object array. But you can do the following:

object[] a = new object[] { (int)1, (int)2 }






or

object b = (object)(new int[] { 1, 2 })





-----------------------



对不起,你的问题与原来的标题不符,转过来。



但最终,它遵循上述规则的反向。您可以将对象数组的内容强制转换为整数。您不能直接使用对象数组的引用来完成它。你必须遍历每个对象并一次抛出一个。



-----------------------

Sorry, getting turned around by your question not matching your original title.

But ultimately, it follows the inverse of the above rules. You can cast the contents of an object array to an integer. You can't just do it directly with the reference of the object array. You have to iterate over each of the objects and cast them one at a time.


如果你使用的是.net 3.5这可能对你有所帮助

if you are using .net 3.5 this might help you
object[] objarr = new object[] {1,2,3 };
 int[] arr= objarr.Cast<int>().ToArray();





它是一个包含在.net 3.5中的简洁方法,允许你投射整个集合。



希望有帮助

祝你好运



its a neat method included with .net 3.5 that allows you to cast the entire collection.

Hope that helped
good luck


这篇关于c#对象数组到int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆