能告诉我如何读取在一个类中声明的枚举的值吗? [英] Could any tell me how to read the values of the enums declared in a class?

查看:78
本文介绍了能告诉我如何读取在一个类中声明的枚举的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!

我正在使用C#中的system.reflection.我必须使用反射来读取枚举值.但是这样做并没有获得值.

有什么可以帮助我完成该过程的吗?

Hi everyone!

I am working on system.reflection in C#. I have to read the enums values using reflection.But while doing am not getting the values.

Can any help me how to do the process?

private void ExtractSampleConstants(Type t)
    {
        FieldInfo[] FInfo = t.GetFields(BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
        foreach (FieldInfo fin in FInfo)
        {
            string ReplaceStr=string.Empty;
            string Fname = fin.Name;
            object Fvalue = fin.GetValue(fin.Name);
            if(t.Name=="SampleConstants")
                ReplaceStr=fin.DeclaringType.Name.ToString()+"."+Fname;
            else
                ReplaceStr = ConvertToShortForm(fin.DeclaringType.FullName.ToString()) + "." + Fname;
            DataDecl.FINFO.Add(new ConstInfo(Fname, Fvalue, ReplaceStr));
        }

推荐答案

如果必须为此使用反射,则替换行
If you must use reflection for this, then replace your line
object Fvalue = fin.GetValue(fin.Name);


with


with

object Fvalue = fin.GetRawConstantValue();


您的意思是序数值?

您所需要做的就是将其强制转换为适当的整数类型.
You you mean the ordinal values?

All you have to do is cast it to the appropriate integer type.


您可以使用Enum类的静态方法:

You could use the static methods of the Enum class:

public enum SomeEnum
{
  SomeItem,
  SomeItem2,
  SomeItem3
}

public void Something()
{
  var values = Enum.GetValues(typeof(SomeEnum));
}



而且您不必费解反射.



and you''ll not have to mess around with reflection.


这篇关于能告诉我如何读取在一个类中声明的枚举的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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