0

我们可以使用 foreach 清除表单中的所有文本框,而无需为每个文本框输入代码来清除它们。

com.Parameters.Add(new SqlParameter("@",objPlayrInjr_P));

using (SqlCommand com = new SqlCommand())
{
    com.CommandText = "SPname";
    com.Connection = connection object;
    com.CommandType = CommandType.StoredProcedure;

    com.Parameters.Add(new SqlParameter("@SqlParameterName",objectName.propertyName));
}

我需要一种通过循环添加sqlParametersCommand对象的方法,就像我在清除文本框时所做的那样。因此无需为每条语句编写代码,它将由循环完成。

4

2 回答 2

3

一种方法是将参数名称和值放在 a 中Dictionary<string, object>,然后

foreach (KeyValuePair<string, object> param in params)
{
    com.Parameters.AddWithValue(param.Key, param.Value);
}
于 2012-08-16T14:47:32.787 回答
3

这是使用注释的东西:

用参数名称标记属性的注解

[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));
    }
}
于 2012-08-16T15:02:50.200 回答