我有下面的代碼可以工作,但想要一個更可重用的或獲得相同的結果。而不是Remove_At_Weight
和Remove_At_Code
函數我想要一個通用的Remove
函數,您可以選擇要比較的字段和要比較的字段。動態刪除功能
因此,例如,我可能會叫另一個對象說Recordo_3
具有第三場 「字符串描述」 ,我要檢查該字段具有寫入新的「Remove_At_Description」功能了。
我可能從錯誤的角度來解決這個問題,並且有更好的方法來使用設計模式等等,如果有的話請告知。希望這是有道理的。
class Recordo
{
private string _code;
public string Code
{
get { return _code; }
set { _code = value; }
}
private int _weight;
public int Weight
{
get { return _weight; }
set { _weight = value; }
}
}
private void Form1_Load(object sender, EventArgs e)
{
List<Recordo> lr = new List<Recordo>();
lr.Add(new Recordo() {Code = "QQQ", Weight = 10});
lr.Add(new Recordo() { Code = "AAA", Weight = 20 });
lr.Add(new Recordo() { Code = "AAA", Weight = 10 });
lr.Add(new Recordo() { Code = "QQQ", Weight = 10 });
lr = Remove_At_Code(lr,"QQQ");
lr = Remove_At_Weight(r, "20");
MessageBox.Show("Done!");
}
private static List<Recordo> Remove_At_Weight(List<Recordo> lr, int weight)
{
for (int i = lr.Count-1; i > -1; i--)
{
if (lr[i].Weight == weight)
{
lr.RemoveAt(i);
}
}
return lr;
}
private static List<Recordo> Remove_At_Code(List<Recordo> lr, string code)
{
for (int i = lr.Count-1; i > -1; i--)
{
if (lr[i].Code == code)
{
lr.RemoveAt(i);
}
}
return lr;
}
使用IComperable接口怎麼樣? - 谷歌它 –
@MatthiasHerrmann IComparable不是必需的。我猜你的意思IEquatable –
@Sriram既會工作 –