![](/img/trans.png)
[英]How do I access the variable of one method from another method within the same class C#?
[英]How to access DisplayMember from within a method of the same class?
我有一个类数据,它的原型成员ReportName定义了稍微不同的显示名称,以便网格列标题更有意义。
现在,我正在实现此类的IDataErrorInfo,以向最终用户显示一条错误消息,说在保存时“报告名称不能为空”。 那么,如何在同一类的私有方法中访问ReportName的显示成员属性?
Class Data
{
[ProtoMember(1), DefaultValue(null), DisplayName("Report Name")]
public string ReportName { get; set; }
//Check if the reportname was entered
private void CheckReportName()
{
//code to check reportname and generate the errormessage containing the colheader to be sent to grid
}
}
何
您可以使用反射:
var displayName = this.GetType()
.GetProperty("ReportName")
.GetCustomAttributes(false)
.OfType<DisplayNameAttribute>()
.First()
.DisplayNameValue;
鉴于Reflection已经需要属性名称的“魔力字符串”来查找值,您可以考虑使用以下类似的方法:
class Data
{
[ProtoMember(1), DefaultValue(null), DisplayName(DisplayNames.ReportName)]
public string ReportName { get; set; }
//Check if the reportname was entered
private void CheckReportName()
{
//code to check reportname and generate the errormessage containing the colheader to be sent to grid
}
private static class DisplayNames
{
public const string ReportName = "Report Name";
}
}
这比基于反射的方法执行得更快,并且(更重要的是)它避免使用硬编码的属性名称来获取属性以找到属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.