能告诉我如何读取在一个类中声明的枚举的值吗?
问题描述:
大家好!
我正在使用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.