简体   繁体   中英

Is it possible to change Type to a given type?

When I have a boxed value such as:

object input = 31.33M;

I can convert it to a convertible type with this method:

public static T ToType<T>( object value)
 {
  return (T) Convert.ChangeType(value,typeof (T));
 }

so both:

Console.WriteLine (ToType<double>(input));
Console.WriteLine (ToType<decimal>(input));

will return

31.33 //as double
31.33 //as decimal

(let's leave aside the precision issues)

Okay.

But now I'm facing ( I'm using WebAPI which exposes method descriptor and its argument types) a situation where I have a given type.

So now I have :

Type SomeoneSaysMyTypeIs=typeof(decimal)

But now I can't use generic type argument.

Question

How can I enhance my method to work for: ( pseudo code )

ToType(SomeoneSaysMyTypeIs,input); //return type :decimal  , not object

I've found solutions but with a lot of if's ...

It can be I didn't understand your question correctly (please tell so if I did), but what about introducing another method:

public static object ToType(object value, Type t)
{
    return Convert.ChangeType(value, t);
}

Which is as you see just the same as calling Convert.ChangeType directly:

Convert.ChangeType(value, t);

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