C# PropertyInfo.GetValue返回枚举常量名称而不是值

C# PropertyInfo.GetValue返回枚举常量名称而不是值,c#,reflection,C#,Reflection,我正在构建一个序列化组件,该组件使用反射来构建序列化数据,但我从枚举属性中得到了奇怪的结果: enum eDayFlags { Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64 } public eDayFlags DayFlags { get; set; } 现在是真正的考验 Obj Test =

我正在构建一个序列化组件,该组件使用反射来构建序列化数据,但我从枚举属性中得到了奇怪的结果:

enum eDayFlags
{
    Sunday = 1,
    Monday = 2,
    Tuesday = 4,
    Wednesday = 8,
    Thursday = 16,
    Friday = 32,
    Saturday = 64
}

public eDayFlags DayFlags { get; set; }
现在是真正的考验

Obj Test = new Obj();
Test.DayFlags = eDayFlags.Friday;
序列化的输出是:

日旗=星期五

但如果我在变量中设置了两个标志:

Obj Test = new Obj();
Test.DayFlags = eDayFlags.Friday;
Test.DayFlags |= eDayFlags.Monday;
序列化的输出是:

日旗=34

我在序列化组件中所做的工作非常简单:

//Loop each property of the object
foreach (var prop in obj.GetType().GetProperties())
{

     //Get the value of the property
     var x = prop.GetValue(obj, null).ToString();

     //Append it to the dictionnary encoded
     if (x == null)
     {
          Properties.Add(HttpUtility.UrlEncode(prop.Name) + "=null");
     }
     else
     {
          Properties.Add(HttpUtility.UrlEncode(prop.Name) + "=" + HttpUtility.UrlEncode(x.ToString()));
     }
}
有人能告诉我如何从PropertyInfo.GetValue获取变量的实际值吗?即使它是枚举且只有一个值

谢谢

您得到了真正的值-这只是转换为字符串,并没有达到预期效果。
prop.GetValue
返回的值将是装箱的
eDayFlags

是否要从枚举中获取数值?将其强制转换为
int
。允许将枚举值取消绑定到其基础类型


请注意,您的枚举(可能应称为
Days
)应该应用
[Flags]
,因为它是一个标志枚举。

这是预期的行为

您没有在枚举上设置
Flags
属性,因此
.ToString()
返回作为其基础类型铸造的枚举的字符串表示形式(
int

添加
[Flags]
将强制您的
.ToString()
返回您的期望值,即
“星期一、星期五”


如果反编译
Enum
类,您将在
ToString()实现中看到如下代码:

//// If [Flags] is NOT present
if (!eT.IsDefined(typeof (FlagsAttribute), false))
//// Then returns the name associated with the value, OR the string rep. of the value
//// if the value has no associated name (which is your actual case)
    return Enum.GetName((Type) eT, value) ?? value.ToString();
else
//// [Flags] defined, so return the list of set flags with
//// a ", " between
    return Enum.InternalFlagsFormat(eT, value);

如果我试图将得到的值强制转换为int,它会说我无法强制转换,因为我得到的是字符串版本,而不是枚举值。@MathieuDumoulin:那将是因为您调用了
ToString
。不要这样做…谢谢,现在一切都正常了,这就是当你在网上复制粘贴部分代码时会发生的事情,因为你不知道如何完成一些事情,你看不到最后的.ToString()并最终问了一些问题,所以:(哦,对不起,我刚刚注意到我在使用ToString,复制/粘贴的美妙世界感谢[Flags]属性,我已将另一个人标记为正确,因为他是第一个回答的人,而且您的两个答案都很好,谢谢您的时间。我建议养成习惯,使用十六进制或位移位而不是十进制来表示标志。对于较低的数字来说,这没什么大不了的,但为了一致性,我会在任何地方都这样做。