我目前正在尝试创建一个 HtmlHelper,它采用与内置帮助器 LabelFor<>、DisplayFor<>、EditorFor<> 等相同的表达式,但专门针对枚举类型:
例如model => model.MyEnumProperty
我是整个 lambda 表达式的新手,尽管到目前为止我做的或多或少都还不错(在 SackOverflow 社区的其他答案的帮助下),我现在在尝试检索对象时遇到以下异常(即,model
)在表达式中:
“从范围''引用'WCSFAMembershipDatabase.Models.Address'类型的变量'模型',但未定义”
public static MvcHtmlString EnumDisplayFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
{
// memberExp represents "model.MyEnumProperty"
MemberExpression memberExp = (MemberExpression)expression.Body;
if (memberExp == null)
{
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
expression.ToString()));
}
// modelExp represents "model"
Expression modelExp = memberExp.Expression;
// Convert modelExp to a Lambda Expression that can be compiled into a delegate that returns a 'model' object
Expression<Func<TModel>> modelLambda = Expression.Lambda<Func<TModel>>(modelExp);
// Compile modelLambda into the delegate
// The next line is where the exception occurs...
Func<TModel> modelDel = modelLambda.Compile();
// Retrieve the 'model' object
TModel modelVal = modelDel();
// Compile the original expression into a delegate that accepts a 'model' object and returns the value of 'MyEnumProperty'
Func<TModel, TEnum> valueDel = expression.Compile();
// Retrieve 'MyEnumProperty' value
TEnum value = valueDel(modelVal);
// return the description or string value of 'MyEnumProperty'
return MvcHtmlString.Create(GetEnumDescription(value));
}
// Function returns the Description Attribute (if one exists) or the string
// representation for the specified enum value.
private static string GetEnumDescription<TEnum>(TEnum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if ((attributes != null) && (attributes.Length > 0))
return attributes[0].Description;
else
return value.ToString();
}
EnumDisplayFor中与表达式相关的代码是根据以下位置的详细信息拼凑而成的:
- http://blogs.msdn.com/b/csharpfaq/archive/2010/03/11/how-can-i-get-objects-and-property-values-from-expression-trees.aspx
- https://stackoverflow.com/a/672212
我确实找到了一些其他问题,它们提到了与 lambda 表达式相关的相同异常,但它们都处于有人手动制作表达式树的上下文中,我无法弄清楚答案中的信息如何适用于我的案例.
如果有人能解释(a)为什么会发生异常以及(b)我如何解决它,我将不胜感激。:-)
提前致谢。