[英]List add extension with properties
我可以通過展示我希望的例子來最好地解釋這一點
我有一個模特
public class TestModel
{
public int Test1 { get; set; }
public string Test2 { get; set; }
}
我做一個清單
List<TestModel> testList = new List<TestModel>
現在最初當我添加一個項目時,我應該使用
testList.Add(new TestModel { Test1 = 1, Test2 = "Test" });
但我希望能夠做的是
testList.Add(1, "Test")
有什么辦法可以做到這一點?
您可以使用擴展方法來執行此操作,但我個人不會。
public static class TestModelListExtensions
{
public static void Add(this List<TestModel> list, int test1, string test2)
{
list.Add(new TestModel { Test1 = test1, Test2 = test2 });
}
}
class Program
{
static void Main(string[] args)
{
List<TestModel> list = new List<TestModel>();
list.Add(1, "hello");
}
}
您可以創建TestModel
的構造函數並執行以下操作:
testList.Add(new TestModel(1, "Test"));
public class TestModel
{
public int Test1 { get; set; }
public string Test2 { get; set; }
public TestModel(int test1, string test2)
{
Test1 = test1;
Test2 = test2;
}
}
嘗試這個
public static class Extensions {
public static List<TestModel> Add(this List<TestModel> list, int test1, string test2) {
return list.Add(new TestModel { Test1 = test1, Test2 = test2 });
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.