如何将枚举转换为类型 [英] How to convert enum to type

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

问题描述

我有一个这样的枚举。

public enum eTypeVar
{
    Int,
    Char,
    Float
};

,我想将其转换为类型,执行以下操作:

and I want to convert it to type , to do something like this:

eTypeVar type=eTypeVar .Int;
string str= eTypeVar.ToString .ToLower();
(str as type) a=1;

我该怎么做?

推荐答案

我想你需要的是:

Dictionary<eTypeVar, Type> _Types = new Dictionary<eTypeVar, Type> {
    { eTypeVar.Int, typeof(Int32) },
    { eTypeVar.Char, typeof(Char) },
    { eTypeVar.Float, typeof(Single) }
};

public Boolean Check(eTypeVar type, Object value)
{
    return value.GetType() == _Types[type];
}

您不能将变量转换为另一个变量声明的类型。你应该重新考虑你的设计。无论如何,它不会使你在做什么。如果你知道你想使用一个int,那么为什么不声明它呢?

You cannot convert a variable into a type for another variable declaration. You should rethink your design. Anyway it doesn't make sence what you are doing. If you know that you want to use a int, why not declare it:

String name = "int";
int value = 1;

如果您想要有动态代码,您可以使用反射和通用方法。

If you want to have dynamic code for some reasons you could use Reflection and a generic method.

public void DoSomething<T>(T value)
{
    ....
}

然后你可以构造在运行时使用反射和调用它。但是在这个时候,我想你需要更多的C#基础来处理这个功能。

Then you can construct the method at runtime using reflection and invoke it. But at this time i think you need more basics of C# to work with this features.

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

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