![](/img/trans.png)
[英]How to pass a list and string into a generic method which has generic list parameter
[英]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: FirstName
, LastName
和PhoneNumber
分別具有一個參數。
無論輸入如何,您都將返回"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.