问题描述
我试图在CSharp中将对象数组转换为通用对象数组,不断收到此编译器错误。任何想法?
谢谢
private const int INITIAL_CAPACITY = 20;
保护int numElements;
保护E []元素;
$ b / *
*创建一个新集合的默认构造函数
*最初为空
* * /
public ArraySet()
{
numElements = 0;
elements =(E [])(new Object [INITIAL_CAPACITY]); //未检查
}
感谢球员,另一个相关的问题,我想设置一个特定的元素为null。以下代码无效。
元素[numElements - 1] = null:
什么是正确的那么我们应该在这里使用null值。感谢
PLB的答案指出了为什么你不需要来做到这一点,
让我们假设你有一个对象数组:
var objectArray = new object [] {3,5,3.3,test};
现在您会如何将其转换为统一的泛型?不能保证对象数组内的所有实例都是相同类型的,这个数组可能是异构的,所以这个:
public static T [] ConvertTo< T>(object [] arr)
{
return(T [])arr;
}
var intArray = ConvertTo< int>(objectArray);
无法真正工作:无法将类型'object []'转换为'
ConvertTo
方法中的'T []'
在这种情况下,如果它是适当的类型,那么可以测试每个项目,特别是因为LINQ已经有适合的方法:
var intArray = objectArray.OfType< int>()。ToArray();
这会给你一个数组: [3,5]
$ b
所以一个通用版本是: elementsArray = objectArray.OfType< E>()。ToArray();
I am trying to cast an object array to generic object array in CSharp, keep getting this compiler error. Any ideas?
Thanks
private const int INITIAL_CAPACITY = 20;
protected int numElements;
protected E[] elements;
/*
* default constructor that creates a new set
* that is initially empty
* */
public ArraySet()
{
numElements = 0;
elements = (E[])(new Object[INITIAL_CAPACITY]);// unchecked
}
thanks guys, Another related question, I want to set a particular element to null. The following code does not work.
elements[numElements - 1] = null:
What is the correct null value we should use in here then. thank
PLB's answer points out why you don't need to do that, I'll just chime in on why you can't do that.
Let's say you have an object array:
var objectArray = new object[] { 3, 5, 3.3, "test" };
Now how would you say I convert that to a uniform, generic type? There's no guarantee that all of the instances inside the object array will be of the same type, the array might be heterogenous, so this:
public static T[] ConvertTo<T>(object[] arr)
{
return (T[])arr;
}
var intArray = ConvertTo<int>(objectArray);
Can't really work: Cannot convert type 'object[]' to 'T[]'
in the ConvertTo
method.
What you can do in such situation is test each and every item if it's of appropriate type, especially since LINQ already has fitting method:
var intArray = objectArray.OfType<int>().ToArray();
Which will give you an array: [3, 5]
So a generic version would be: elementsArray = objectArray.OfType<E>().ToArray();
这篇关于如何将对象数组转换为泛型类型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!