[英]Casting with Type object
I want to use GetType() method to get the Type of the variable then cast some other variable to this type. 我想使用GetType()方法来获取变量的类型,然后将其他变量转换为该类型。 For example, I have an Int32 i, a Double d, I want to get Type of d (in general case) then cast i to d's Type then grant i's value to d.
例如,我有一个Int32 i,一个Double d,我想获取d的Type(通常情况下),然后将i转换为d的Type,然后将i的值赋给d。
Int32 i = 123;
Double d = 0.0;
Type t = d.GetType();
d = Conversion.CastExamp1 < t > (i);
d = Conversion.ConvertExamp1 < t > (i);
PS: @Zyphrax: i have used your post here Casting a variable using a Type variable but when compiling, it says that "The type or namespace name 't' could not be found...". PS:@Zyphrax:我在这里用过您的文章, 使用Type变量转换了一个变量,但是在编译时,它说“找不到类型或名称空间名称't'...”。 So could you please describe more detail how to use your code?
因此,您能否详细描述如何使用代码?
You cannot use Type
as a generic parameter, this must be an object that can be constructed which Type
cannot. 您不能将
Type
用作通用参数,这必须是Type
不能构造的对象。 The closes you will get is by using objects as parameters 您将获得的关闭是通过使用对象作为参数
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Int32 i = 123;
Double d = 0.0;
Type t = d.GetType();
// Print the type of d
Console.WriteLine(t.Name); // "Double"
var newI = DoStuff(t, i);
// Print the new type of i
Console.WriteLine(newI.GetType().Name); // "Double"
Console.Read();
}
public static object DoStuff(object type, object inData)
{
Type newType = (Type)type;
// Fix nullables...
Type newNullableType = Nullable.GetUnderlyingType(newType) ?? newType;
// ...and change the type
return Convert.ChangeType(inData, newNullableType);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.