我正在尝试强烈键入模型验证异常。我有一个以表达式为参数的通用异常类。我需要捕获该通用异常并从表达式中检索字段名称。问题在于它是通用的,这并不容易。
FieldValidationException.cs:
public class FieldValidationException<TModel> : Exception where TModel : class {
public Expression<Func<TModel, object>> Field { get; }
public FieldValidationException(string message, Expression<Func<TModel, object>> field) : base(message) {
Field = field;
}
}
MyModelValidator.cs:
try {
throw new FieldValidationException<MyModel>("Error", model => model.userId)
} catch (Exception ex) {
if (ex.GetType().GetGenericTypeDefinition() == typeof(FieldValidationException<>)) {
Expression<Func<object, object>> field = ??? //How do I retrieve the field?
fieldName = expression.Member.Name;
Debug.WriteLine(fieldName);
}
}
答案 0 :(得分:0)
我通过从FieldValidationException
而不是捕获类中的成员表达式中检索字段名称来解决了这个问题。
FieldValidationException.cs:
public class FieldValidationException<TModel> : Exception where TModel : class {
public string FieldName { get; }
public FieldValidationException(string message, Expression<Func<TModel, object>> field) : base(message) {
FieldName = (MemberExpression)field.Body.Member.Name;
}
}
然后,我可以使用反射来获取字段名称:
MyModelValidator.cs:
if (ex.GetType().GetGenericTypeDefinition() == typeof(FieldValidationException<>)) {
PropertyInfo fieldNameProperty = ex.GetType().GetProperty("FieldName");
var fieldName = fieldNameProperty.GetValue(ex) as string;
}