这是使用注释的东西:
用参数名称标记属性的注解
[AttributeUsage(AttributeTargets.Property)]
public class ParameterAttribute : Attribute
{
public string ParameterName { get; private set; }
public ParameterAttribute(string parameterName)
{
ParameterName = parameterName;
}
}
示例类
public class Person
{
[Parameter("FirstName")]
public string FirstName { get; set; }
[Parameter("LastName")]
public string LastName { get; set; }
[Parameter("EmailAddress")]
public string Email { get; set; }
}
用法
SqlCommand command = new SqlCommand();
Person person = new Person()
{
FirstName = "John",
LastName = "Doe",
Email = "johndoe@domain.com"
};
foreach (var pi in person.GetType().GetProperties())
{
var attribute = (ParameterAttribute)pi.GetCustomAttributes(typeof(ParameterAttribute), false).FirstOrDefault();
if (attribute != null)
{
command.Parameters.AddWithValue(string.Format("@{0}", attribute.ParameterName), pi.GetValue(person, null));
}
}