gpt4 book ai didi

c# - 使用 Enum as/with 表达式?

转载 作者:行者123 更新时间:2023-12-02 21:52:03 25 4
gpt4 key购买 nike

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

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
}

最佳答案

您不需要为此使用表达式。您需要知道的是,enum 的每个值都有一个字段。这意味着您可以执行以下操作:

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# - 使用 Enum as/with 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18404388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com