简体   繁体   中英

How to convert value of Generic Type Argument to a concrete type?

I am trying to convert the value of the generic type parameter T value into integer after making sure that T is in fact integer:

public class Test
{
    void DoSomething<T>(T value)
    {
        var type = typeof(T);
        if (type == typeof(int))
        {
            int x = (int)value; // Error 167 Cannot convert type 'T' to 'int'
            int y = (int)(object)value; // works though boxing and unboxing
        }
    }
}

Although it works through boxing and unboxing, this is an additional performance overhead and i was wandering if there's a way to do it directly.

Boxing and unboxing is going to be the most efficient way here, to be honest. I don't know of any way of avoiding the boxing occurring, and any other form of conversion (eg Convert.ToInt32) is potentially going to perform conversions you don't actually want.

Convert.ToInt32(value); 

应该这样做。

int x = (dynamic)MyTest.Value;

I know this is a very old thread, but this is the actual way to do it. (dynamic) will convert the T value to any of the primitive known type in runtime.

int and the other CLR primitives implement IConvertible .

public class Test
{
    void DoSomething<T>(T value) where T : IConvertible
    {
        var type = typeof(T);
        if (type == typeof(int))
        {
            int y = value.ToInt32(CultureInfo.CurrentUICulture);
        }
    }
}

See my answer to another post: https://stackoverflow.com/a/26098316/1458303 . It contains an effective class implementation which avoids boxing during conversion.

int id = (dynamic)myobject.SingleOrDefault();

OR

int id = (int)myobject.SingleOrDefault();

It worked for me to get the int value. Here myobject is having ObjectResult<Nullable<int>> value.

以下方式应该有效。

int x = (int)(value as int?);

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