繁体   English   中英

如何将 object 转换为 Type?

[英]How to cast an object to Type?

我想将object转换为 System.Type object 定义的类型 我只知道objectType作为输入,我不能添加type parameters

void Test()
{
    object obj = 3;
    Type type = typeof(int);

    int number = Cast(obj, type);

    Console.WriteLine($"{number}, {number.GetType()}"); // Should output "3, System.Int32"
}

// I can't change the inputs
??? Cast(object obj, Type type)
{
    // return the obj casted to type, but how?
}

我想有一种方法可以使用反射来解决它,但我找不到这样的东西。

您可以使用ChangeType方法:

1 - 铸造方法:

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

2 - 测试方法:

void Test()
{
    object obj = 3;

    int number = Cast<int>(obj);

    Console.WriteLine($"{number}, {number.GetType()}");
}

结果

3, System.Int32

我希望你觉得这有帮助。

可以在不将 Cast 方法更改为模板的情况下执行此操作。 它需要返回动态类型。 要进行转换,您应该使用Convert.ChangeType方法。

//I can't change the inputs
dynamic Cast(object obj, Type type)
{
    // return the obj casted to type, but how?
    return Convert.ChangeType(obj, type);
}

暂无
暂无

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

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