[英]Type conversion in C#, where is my error?
I "grew up" on Java and have recently made a full switch to C#. 我“成长”在Java上,最近完全转向了C#。 I am just teaching myself ATM, and just going back, redoing all my old programming assignments that were in Java using C# now.
我只是在自学ATM,然后回去,现在重做所有我以前使用C#在Java中编写的旧程序。 Here is a particular line of code where I am trying to use generics and instantiate the stack array.
这是我尝试使用泛型并实例化堆栈数组的特定代码行。
stack = (T[])(new object[def_cap]);
which gives me this compiler error 这给了我这个编译器错误
Cannot convert type 'object[]' to 'T[]' (CS0030)
Cannot implicitly convert type 'object[]' to 'T[]' (CS0029)
I guess the cast operator works differently in C# than in Java, and was wondering if anyone could enlighten me. 我想强制转换运算符在C#和Java中的工作方式不同,并且想知道是否有人可以启发我。 Thank you!
谢谢!
Just use stack = new T[def_cap];
只需使用
stack = new T[def_cap];
instead. 代替。 You already have the type and are able to use it directly.
您已经具有该类型,并且可以直接使用它。
To convert an array to another type, you could do: 要将数组转换为其他类型,可以执行以下操作:
object[] objArr = new object[10];
T[] tArr = objArr.Cast<T>().ToArray();
Note that if the objects cannot be casted to type T
, it will throw InvalidCastException
on runtime. 请注意,如果无法将对象
InvalidCastException
为T
类型,则它将在运行时引发InvalidCastException
。
C# supports array covariance for reference-types only. C#仅支持引用类型的数组协方差 。 So you must constraint generic parameter T to class:
因此,您必须将通用参数T约束为类:
public static void Foo<T>() where T:class
{
T[] stack = (T[])(new object[def_cap]);
}
But in your case, where you are casting object[] to T[], you will get InvalidCastException at runtime unless T is System.Object, because array covariance can cast X[] to Y[] only if Y is the same type as X or if X is class derived from Y (but not if Y is derived from X). 但是在您的情况下,将object []强制转换为T []时,除非T为System.Object,否则在运行时将获得InvalidCastException,因为仅当Y与以下类型相同时,数组协方差才能将X []强制转换为Y [] X或X是从Y派生的类(但如果Y是从X派生则不是)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.