如何对象转换值类型的值? [英] How to cast an object value to Type values?

查看:210
本文介绍了如何对象转换值类型的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的类型:

public class TypeValue
{
    public Type Type { get; private set; }
    public object Value { get; private set; }
}

所以我可以做这样的事情:

so I can do something like:

TypeValue tv = ...
int count = (tv.Type) tv.Value;

但是编译器是给我这个错误:

but the compiler is giving me this error:

类型或命名空间名称'电视'可能   未找到(是否缺少使用   指令或程序集引用?)

The type or namespace name 'tv' could not be found (are you missing a using directive or an assembly reference?)

我如何做到这一点?

推荐答案

您应该只是做:

TypeValue tv = ...
int count = (int) tv.Value;

见,在情况下,你知道在编译时的类型(在这种情况下,你知道,计数 INT ),那么就没有一点参考 tv.Type 反正。这有助于说明为什么这样做没有逻辑意义,因而是不可能的。

See, in the case where you know the type at compile-time (in this case you know that count is an int), then there's no point referring to tv.Type anyway. This helps illustrate why this doesn't make logical sense and thus is not possible.

这篇关于如何对象转换值类型的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆