简体   繁体   English

是否可以将Type更改为给定类型?

[英]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. 但是现在我正面临着(我正在使用公开方法描述符及其参数类型的WebAPI)我有一个给定类型的情况。

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 ... 我找到了解决方案,但有很多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相同:

Convert.ChangeType(value, t);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM