Can you make an object long in C #?

I am pulling the "long" value from the session using the generic property, and it fails.

so I:

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

    ...
}

When debugging, the value is 4, and it will work.

+3
source share
3 answers

If you insist on keeping your general 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));

    ...
}

This will allow you to call:

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

But be careful: Convert.ChangeType () does not work for all conversions.

+8
source

Use Convert.ToInt64

+6
source

, , :

(100 ), ( ), , , .

.net :

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

, "", . ,

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

I actually change the nature of things, dand ldo not have the same representation, one is a double-wide floating point with a value of 3.7, and the other is a 64-bit integer with a value of 3.

The .net statement can do both of these things, however it won’t do them at the same time, and that’s 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, a shameless copy of the wizard ( here for more detailed explanations )

+2
source

Source: https://habr.com/ru/post/1750371/


All Articles