I can best explain this by showing a example of what I wish
I have a model
public class TestModel
{
public int Test1 { get; set; }
public string Test2 { get; set; }
}
I make a list
List<TestModel> testList = new List<TestModel>
now originally when I add a item I should use
testList.Add(new TestModel { Test1 = 1, Test2 = "Test" });
but what I wish to be able to do is
testList.Add(1, "Test")
Is there any way to accomplish this ?
You could use an extension method to do it, but I wouldn't personally.
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");
}
}
You could create a constructor of your TestModel
and do:
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;
}
}
try this
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 });
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.