在 C# 中获取属性名称
本文关键字:属性 获取 | 更新日期: 2023-09-27 18:33:48
我有一个验证类,我想验证从 Web 服务收到的各种属性是否有效,如果无效,则报告描述性错误消息。
目前 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;
}
}
在Visual Studio 2011中,有一个新功能可以处理这个问题:http://www.mitchelsellers.com/blogs/2012/02/29/visual-studio-11-caller-member-info-attributes.aspx
在当前/旧版本中,您必须使用诸如Oblivion2000之类的技巧
以下是克林顿·谢泼德(Clinton Sheppard)对此的帖子:http://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/
它对我来说非常有用,我把它放在我的书签中。就个人而言,我喜欢他的静态嵌套类方式(引自上面):
public class Sample2
{
public static class BoundPropertyNames
{
public static readonly string Foo = ((MemberExpression)((Expression<Func<Sample2, int>>)(s => s.Foo)).Body).Member.Name;
}
public int Foo { get; set; }
}