我有一个验证类,在此我想验证从 Web 服务接收到的各种属性是否有效,如果不是,则报告描述性错误消息。
目前,网络服务返回所有字符串,我想将这些转换/验证为更有用的类型。问题是我目前在方法调用中将属性名称作为字符串参数传递。有没有办法在不将其作为字符串传递的情况下获取要在错误消息中显示的属性名称?
public class WebserviceAccess
{
public MyUsefulDataObject ConvertToUsefulDataObject(WebserviceResponse webserviceResponse)
{
var usefulData = new MyUsefulDataObject();
usefulData.LastUpdated = webserviceResponse.LastUpdated.IsValidDateTime("LastUpdated");
// etc . . .
// But I don't want to have to pass "LastUpdated" through.
// I'd like IsValidDateTime to work out the name of the property when required (in the error message).
return usefulData ;
}
}
public static class WebServiceValidator
{
public static DateTime IsValidDateTime(this string propertyValue, string propertyName)
{
DateTime convertedDate;
if (!DateTime.TryParse(propertyValue, out convertedDate))
{
throw new InvalidDataException(string.Format("Webservice property '{0}' value of '{1}' could not be converted to a DateTime.", propertyName, propertyValue));
}
return convertedDate;
}
}
非常感谢任何帮助。
提前致谢。
编辑:使用 Oblivion2000 的建议,我现在有以下内容:
public class Nameof<T>
{
public static string Property<TProp>(Expression<Func<T, TProp>> expression)
{
var body = expression.Body as MemberExpression;
if (body == null)
{
throw new ArgumentException("'expression' should be a member expression");
}
return body.Member.Name;
}
}
public class WebserviceAccess
{
public MyUsefulDataObject ConvertToUsefulDataObject(WebserviceResponse webserviceResponse)
{
var usefulData = new MyUsefulDataObject();
usefulData.LastUpdated = Nameof<WebserviceResponse>.Property(e => e.LastUpdated).IsValidDateTime(webserviceResponse.LastUpdated);
// etc . . .
return usefulData ;
}
}
public static class WebServiceValidator
{
public static DateTime IsValidDateTime(this string propertyName, string propertyValue)
{
DateTime convertedDate;
if (!DateTime.TryParse(propertyValue, out convertedDate))
{
throw new InvalidDataException(string.Format("Webservice property '{0}' value of '{1}' could not be converted to a DateTime.", propertyName, propertyValue));
}
return convertedDate;
}
}