繁体   English   中英

列出带有属性的添加扩展

[英]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.

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