简体   繁体   中英

Cast from generic to generic

In a nutshell I'm trying to get this code working:

class it<X>
{
    X[] data;
    int pos;

    public Y get<Y>()
    {
        return (Y) data[pos];
    }
}

Basically, I have lots of arrays of different primitives that needs to be processed another place as different primitives. The former code won't compile because the compiler doesn't know what X and Y is. The following, does, however:

    public Y get<Y>()
    {
        return (Y) (object) data[pos];
    }

However, then I get runtime exceptions like:

InvalidCastException: Cannot cast from source type to destination type.
it[System.Double].get[Single]()

Which seems silly because C# obviously has a cast between floats and doubles (and other primitives). I'm guessing it has something to do with boxing and such, but I'm pretty new to C# so I don't really know - I guess I'm used to C++ templates. Note that a conversion between X and Y always exists - can I tell the compiler this, some way?

You could use Convert 's ChangeType -method:

public Y get<Y>()
{
    return (Y)Convert.ChangeType(data[pos], typeof(Y));
}

It might also be a good idea to add some generic constraints to your class and method to ensure only primitives can be passed:

class it<X> where X : struct

public Y get<Y>() where Y : struct

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