开发者

Can you cast an object to a long in c#?

开发者 https://www.devze.com 2023-01-03 13:32 出处:网络
I am pulling a \'long\' value from Session, using a generic p开发者_如何学编程roperty, and it is crashing.

I am pulling a 'long' value from Session, using a generic p开发者_如何学编程roperty, and it is crashing.

so I have:

public static T Get<T>(string key)
{
    if(...)
        return (T)System.Web.HttpContext.Current.Session[key];

    ...
}

When debugging, the value is 4, and it crashes.


If you insist on keeping your generic method, you can use Convert.ChangeType():

public static T Get<T>(string key)
{
    if (...)
        return 
          (T) Convert.ChangeType(System.Web.HttpContext.Current.Session[key],
                                 typeof(T));

    ...
}

That will allow you to call:

long n = Get<long>("sessionkey");

But be careful: Convert.ChangeType() doesn't work for all conversions.


Use Convert.ToInt64


So, here's where the problem is:

You had a decimal (100m), that got boxed into an object (while in session) and you are trying to unbox it into a long, and this is where the things hit the fan.

The cast operator in .net does two things actually:

object o="string";
string s=(string) o

here the value of the object never changed, it was the same old "string", if was only its reference that changed. However, when I do

double d= 3.7;
long l = (long) x;

I am actually changing the very nature of the thing, the d and l do not have the same representation, one is a double-width floating point with a value of 3.7, and the other is a 64-bit integer with a value of 3.

The .net operator can do both these things, however, it wont do them at the same time, and thats where your problem was...

decimal d=4m;
object o = d;
long l1 = (long)o; //blows up, the runtime error you got
long l2 = (decimal)o; //compile time error
long l3 = (long)(decimal)o; //first we unbox, then we convert - works

BTW, shameless rip of the master (here for more and better explanations)

0

精彩评论

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

关注公众号