繁体   English   中英

如何将通用列表参数传递给方法?

[英]how to pass generic list parameter into a method?

我正在将电话联系人放入列表<>,并将其保存在数据库中。 下面是我的代码。

这是我获取联系人列表的方法

protected override void OnCreate(Bundle bundle) {
    base.OnCreate(bundle);
    try {
        SetContentView(Resource.Layout.Main);
        TextView txtcount = this.FindViewById<TextView>(Resource.Id.textView1);

        List<PersonContact> a1 = GetPhoneContacts();

        Phone gp = new Phone();

        gp.insertContact(a1);
    } catch (System.Exception ex) {
        alert(ex.Message);
    }
}

通过以下方法,我试图将联系人存储在数据库中

[WebMethod]
public string insertContact<T>(List<PersonContact> a) {
    OpenConnection();
    if (a.Count > 0) {
        for (int i = 0; i < a.Count; i++) {
            string str = "insert into phone_contact (FirstName,LastName,PhoneNumber)values('" + a[i].FirstName + "','" + a[i].LastName + "','" + a[i].PhoneNumber + "')";
            SqlCommand cmd = new SqlCommand(str, con);
            cmd.ExecuteNonQuery();
        }
        return "1";
    } else {
        return "1";
    }
}

public class PersonContact {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNumber { get; set; }
}

传递参数时出现错误

 gp.insertContact(a1);

您的方法是通用的,因为它引入了新的类型参数T 这就是方法名称末尾的<T>的含义。

但是,您不会在任何地方使用 T只需将其设为非泛型方法即可:

public string InsertContact(List<PersonContact> a)

同时,我强烈建议您更改进行数据库访问的方式:它目前容易受到SQL注入攻击的攻击。 相反,您应该使用参数化的SQL: FirstNameLastNamePhoneNumber分别具有一个参数。

无论输入如何,您都将返回"1" 您的方法可以更简单地写为:

// Consider renaming to InsertContacts, as it's not just dealing with a single
// contact
public string InsertContact(List<PersonContact> contacts)
{
    // You should almost certainly use a using statement here, to
    // dispose of the connection afterwards
    OpenConnection();
    foreach (var contact in contacts)
    {
        // Insert the contact. Use a using statement for the SqlCommand too.
    }
    return "1";
}

这是假设您根本需要返回的值-如果始终返回相同的值,为什么不将其void方法呢?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM