简体   繁体   中英

Type conversion in C#, where is my error?

I "grew up" on Java and have recently made a full switch to C#. I am just teaching myself ATM, and just going back, redoing all my old programming assignments that were in Java using C# now. 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. Thank you!

Just use 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.

C# supports array covariance for reference-types only. So you must constraint generic parameter T to class:

    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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM