如何从 C# 中的未知枚举中获取值?

发布于 2025-01-03 09:26:14 字数 191 浏览 4 评论 0原文

我实际上正在编写一个扩展对象的 deepToString-Method 。这使用反射来获取对象的每个属性并调用该属性的 deepToString-Method。除了枚举之外,一切都工作正常。如果我尝试将 PropertyInfo.GetValue() 与枚举一起使用,它总是返回零。

我怎样才能得到真正的int值?我缺少什么?

I'm actually programming a deepToString-Method that extends object. This uses reflection to get each property of an object and calls the deepToString-Method for this property. Everything works fine except of Enums. If I try to use PropertyInfo.GetValue() with an enum, it allways returns zero.

How can I get the real int-Value? What am I missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅沫记忆 2025-01-10 09:26:14
foreach (PropertyInfo propertyInfo in your_class.GetType().GetProperties())
{
  if ((info.PropertyType.IsEnum) && (info.PropertyType.IsPublic))
  {
    foreach (FieldInfo fInfo in this.propertyInfo.PropertyType.GetFields(BindingFlags.Public | BindingFlags.Static))
    {
      ListItem item = new ListItem(fInfo.Name, fInfo.GetRawConstantValue().ToString());
      //... use it
    }
  }
}

我必须补充一点,反思是邪恶的。真正需要它的场合很少见。

foreach (PropertyInfo propertyInfo in your_class.GetType().GetProperties())
{
  if ((info.PropertyType.IsEnum) && (info.PropertyType.IsPublic))
  {
    foreach (FieldInfo fInfo in this.propertyInfo.PropertyType.GetFields(BindingFlags.Public | BindingFlags.Static))
    {
      ListItem item = new ListItem(fInfo.Name, fInfo.GetRawConstantValue().ToString());
      //... use it
    }
  }
}

I have to add that reflection is EVIL. Rare are the occasions where it is really needed..

夜光 2025-01-10 09:26:14
public enum Foo
{
    Boo,
    Koo
}

public Foo foo { get; set; }

[Fact]
public void FactMethodName()
{
    foo = Foo.Koo;
    var propertyInfo = this.GetType().GetProperty("foo");
    if (propertyInfo.PropertyType.IsEnum)
    {
        var value = propertyInfo.GetValue(this, null);
        Console.Out.WriteLine("value = {0}", value); //prints Koo
        int asInt = (int)value;
        Console.Out.WriteLine("asInt = {0}", asInt); //prints 1
    }
}
public enum Foo
{
    Boo,
    Koo
}

public Foo foo { get; set; }

[Fact]
public void FactMethodName()
{
    foo = Foo.Koo;
    var propertyInfo = this.GetType().GetProperty("foo");
    if (propertyInfo.PropertyType.IsEnum)
    {
        var value = propertyInfo.GetValue(this, null);
        Console.Out.WriteLine("value = {0}", value); //prints Koo
        int asInt = (int)value;
        Console.Out.WriteLine("asInt = {0}", asInt); //prints 1
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文