开发者

Generics problem

开发者 https://www.devze.com 2023-03-01 06:59 出处:网络
I\'m making a class so I can cheat at minesweeper, and is currently building up some generics... but I\'m kinda stuck. I want to return a int but how do i convert it?

I'm making a class so I can cheat at minesweeper, and is currently building up some generics... but I'm kinda stuck. I want to return a int but how do i convert it?

public T ReadMemory<T>(uint adr)
{
    if( address != int.MinValue )
        if( typeof(T) == typeof(int) )
            return C开发者_如何学Convert.ChangeType(MemoryReader.ReadInt(adr), typeof(T));
        else
            MessageBox.Show("Unknown read type");
}


You need to cast the return value from the call to ChangeType

return (T)Convert.ChangeType(MemoryReader.ReadInt(adr), typeof(T)); 


Try casting:

return (T)Convert.ChangeType(MemoryReader.ReadInt(adr), typeof(T));


I have tried to fix the compiler errors. But I don't know if this is exactly what you are looking for.

You have to cast the result to T

return (T)Convert.ChangeType( MemoryReader.ReadInt( adr ), typeof( T ) );

and you have to return a value when the conditions fail:

return default( T );

This results in:

public T ReadMemory<T>( uint adr )
{
    if ( adr != int.MinValue )
    {
        if ( typeof( T ) == typeof( int ) )
        {
            return (T)Convert.ChangeType( MemoryReader.ReadInt( adr ), typeof( T ) );
        }
        else
        {
            System.Windows.Forms.MessageBox.Show( "Unknown read type" );
        }
    }
    return default( T );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消