如何在使用filehelper库时获取属性名称

时间:2014-07-23 10:13:51

标签: c#

我正在使用FileHelper库。实际上我想在读取文件后记录错误。因此,在记录错误时,我想要映射类的属性名称。那我怎么能这样做呢。

说我的班级是 -

public class Employee
{
  public string EmployeeName;
  public string EmployeeCity
}

对于这个类,假设employeename是强制性的,所以我将在文件读取后验证我的记录,所以现在我要记录一条消息," EmployeeName是强制性的"所以我希望EmployeeName应该是动态的。我能做到吗?

1 个答案:

答案 0 :(得分:0)

我认为你需要反思。您可以使用YourClassInstance.GetType().GetProperties()来获取对象的属性列表。 public string EmployeeName; - 这是一个领域。 public string EmployeeName {get;set;} - 这是一个道具。但你提到了强制性的。你怎么认识到强制性的?我可以假设你用一种自定义属性标记它们:

[AttributeUsage(AttributeTargets.Property)]
public class MandatoryAttribute:System.Attribute
{
}
public class Employee
{
  [Mandatory]
  public string EmployeeName{get;set;}
  [Mandatory]   
  public string EmployeeCity{get;set;}

  public string EmployeeAccount{get;set;}
}

现在,您可以获取以下对象的强制道具名称列表:

Employee c=new Employee();
var propNames= c.GetType().GetProperties().Where(pinf=>pinf.GetCustomAttributes(true).FirstOrDefault(a => a.GetType()==typeof(MandatoryAttribute))!=null).ToList().Select(d=>d.Name);

这将为您提供一个包含{“EmployeeName”,“EmployeeCity”}

的列表

修改

 var EmployeeCollection=Helper.GetEmployees();
    foreach(var employee in  EmployeeCollection)
    {
    foreach(var prop in employee.GetType().GetProperties())
    {
    string val=(string)prop.GetValue(employee,null);
    if(String.IsNullOrEmpty(val)) Helper.Log(prop.Name);
    }
}