C#设置一长串类值的整洁方法?

C#设置一长串类值的整洁方法?,c#,coding-style,refactoring,C#,Coding Style,Refactoring,我有一个有60个不同字符串的类。我需要从一个API中获取字符串,其中字符串有一个名称,保存它们,然后将它们插入到另一个数据库中 所以我的代码是60行代码,看起来像这样 var data = (from l in resultsxml.Root.Descendants(ns + "contacts").Elements(ns + "contact") select new contact { id = (string)l.Element("

我有一个有60个不同字符串的类。我需要从一个API中获取字符串,其中字符串有一个名称,保存它们,然后将它们插入到另一个数据库中

所以我的代码是60行代码,看起来像这样

var data = (from l in resultsxml.Root.Descendants(ns + "contacts").Elements(ns + "contact")
select new contact {
id                              = (string)l.Element("id").Value,
surname                         = (string)l.Element("lastName").Value,
companyName                     = (string)l.Element("organisationName").Value,
...
cmd.Parameters(new SqlParameter("@LastName", i.surname));
cmd.Parameters(new SqlParameter("@DivisionName", i.companyName));
...
然后再加上60行这样的

var data = (from l in resultsxml.Root.Descendants(ns + "contacts").Elements(ns + "contact")
select new contact {
id                              = (string)l.Element("id").Value,
surname                         = (string)l.Element("lastName").Value,
companyName                     = (string)l.Element("organisationName").Value,
...
cmd.Parameters(new SqlParameter("@LastName", i.surname));
cmd.Parameters(new SqlParameter("@DivisionName", i.companyName));
...
以及类声明


是否有一种更整洁的方法来编写此文件,以便我可以循环60个字符串并将名称信息存储在类中?

您可以使用属性类:

public class ElementAndParamNameAttribute : Attribute
{
  public string Element {get;set;}
  public string Param {get;set;}
}
.
.
.
public class contact
{
   [ElementAndParamNameAttribute(Element="lastName",Param="@lastName")]
   public string surname {get;set;}
   .
   .
   .
}

然后使用
typeof(contact).GetProperties()
循环查看
contact
的属性,使用
PropertyInfo.GetCustomAttributes()
查找属性,使用
PropertyInfo.GetValue()
设置值,然后使用
PropertyInfo.SetValue()获取值

您可以使用属性类:

public class ElementAndParamNameAttribute : Attribute
{
  public string Element {get;set;}
  public string Param {get;set;}
}
.
.
.
public class contact
{
   [ElementAndParamNameAttribute(Element="lastName",Param="@lastName")]
   public string surname {get;set;}
   .
   .
   .
}

然后使用
typeof(contact).GetProperties()
循环查看
contact
的属性,使用
PropertyInfo.GetCustomAttributes()
查找属性,使用
PropertyInfo.GetValue()
设置值,然后使用
PropertyInfo.SetValue()获取值

Xml
本身作为参数传递并在数据库中执行映射(逻辑)不是很好吗?将
Xml
本身作为参数传递并在数据库中执行映射(逻辑)不是很好吗?