【问题标题】:Using Enum as/with expressions?使用枚举作为/与表达式?
【发布时间】:2013-08-26 14:19:47
【问题描述】:

是否可以使用带有表达式的枚举来反映枚举值?考虑这个假设的例程:

public enum Fruit
{
  Apple,
  Pear
}

public void Foo(Fruit fruit)
{
  Foo<Fruit>(() => fruit);
}

public void Foo<T>(Expression<Func<T>> expression)
{
    //... example: work with Fruit.Pear and reflect on it
}

Bar() 会给我有关枚举的信息,但我想使用实际值。

背景:我一直在添加一些帮助方法来返回类型的 CustomAttribute 信息,并想知道是否可以对枚举使用类似的例程。

我完全知道您可以使用枚举类型以这种方式获取 CustomAttributes。

更新:

我在 MVC 中使用了类似的概念和辅助扩展:

public class HtmlHelper<TModel> : System.Web.Mvc.HtmlHelper<TModel>
{
    public void BeginLabelFor<TProperty>(Expression<Func<TModel, TProperty>> expression)
    {
        string name = ExpressionHelper.GetExpressionText(expression);
    }
}

在此示例中,name 将是模型的成员名称。我想对枚举做类似的事情,所以名称将是枚举“成员”。这甚至可能吗?

更新示例:

public enum Fruit
{
  [Description("I am a pear")]
  Pear
}

public void ARoutine(Fruit fruit)
{
  GetEnumDescription(() => fruit); // returns "I am a pear"
}

public string GetEnumDescription<T>(/* what would this be in a form of expression? Expression<T>? */)
{
  MemberInfo memberInfo;
  // a routine to get the MemberInfo(?) 'Pear' from Fruit - is this even possible?

  if (memberInfo != null)
  {
    return memberInfo.GetCustomAttribute<DescriptionAttribute>().Description;
  }

  return null; // not found or no description
}

【问题讨论】:

  • 您的意思是让 Foo 调用 Bar 吗?你为什么在这里使用表达式树?你到底想达到什么目的?您的问题目前非常模糊。
  • @JonSkeet 抱歉,发帖前要更改的情况。我已对其进行了更新,还添加了一个用于 Mvc 的例程示例,其中为标签提取了属性名称。
  • 目前还不清楚你为什么不直接调用ToString(),它会为你提供与值关联的名称。
  • 我对枚举名称不感兴趣,我想知道您是否可以使用相同的表达式技术来检索枚举属性。 This question 描述了如何使用反射获取枚举值的自定义属性。考虑到这种方法涉及 MemberInfo - 是否不可能使用带有枚举的表达式来获取值的 MemberInfo 并以这种方式获取属性?
  • “枚举属性”是什么意思?您说“名称将是枚举'成员'”-假设您的意思是“梨”或“苹果”,这正是您从ToString 得到的。如果这不是你想要的,你真的需要给出一个完整的例子来说明你打算如何调用Foo(Fruit) 以及你期望的结果。

标签: c# linq-expressions


【解决方案1】:

您不需要Expressions。您只需要知道enums 的每个值都有一个字段。这意味着您可以执行以下操作:

public static string GetEnumDescription<T>(T enumValue) where T : struct, Enum
{
    FieldInfo field = typeof(T).GetField(enumValue.ToString());

    if (field != null)
    {
        var attribute = field.GetCustomAttribute<DescriptionAttribute>();

        if (attribute != null)
            return attribute.Description;
    }

    return null; // not found or no description
}

【讨论】:

  • 从 C# 7.3 你可以使用where T : Enum
猜你喜欢
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
相关资源
最近更新 更多