C# 使用多个命令预定义类中的字段

C# 使用多个命令预定义类中的字段,c#,attributes,command,predefined-variables,C#,Attributes,Command,Predefined Variables,假设这个类有一个构造函数,它用两个条目填充内部列表: class MyClass { IList<int> someList; public MyClass() { someList = new List<int>(); someList.Add(2); someList.Add(4); ... // do some other stuff } } class-MyCla

假设这个类有一个构造函数,它用两个条目填充内部列表:

class MyClass
{
    IList<int> someList;

    public MyClass()
    {
        someList = new List<int>();
        someList.Add(2);
        someList.Add(4);

        ... // do some other stuff
    }
}
class-MyClass
{
IList someList;
公共MyClass()
{
someList=新列表();
添加(2);
添加(4);
…//做些别的事
}
}
现在让我们假设我有几个构造函数,它们都对内部列表执行相同的操作(但在其他方面有所不同)

我想知道我是否可以将列表的生成和填写直接外包给现场,如下所示:

class MyClass
{
    IList<int> someList = new List<int>(); someList.Add(2); someList.Add(4);
    // Does not compile.

    public MyClass()
    {
        ... // do some other stuff
    }
}
Customer c1 = new Customer()  
                  .FirstName("matt")
                  .LastName("lastname")
                  .Sex("male")
                  .Address("austria");
class-MyClass
{
IList someList=new List();someList.Add(2);someList.Add(4);
//不编译。
公共MyClass()
{
…//做些别的事
}
}

是否可以在字段定义中调用多个命令,如果可以,如何调用?

您可以像这样预实例化
IList
,并在每次访问索引器时添加值:

IList<int> someList = new List<int>() { 2, 4 };

更新2 在阅读了上一篇评论之后,您正在实例化过程中寻找
Fluent接口
。这是一种将函数链接在一起的方法,看起来像这样:

class MyClass
{
    IList<int> someList = new List<int>(); someList.Add(2); someList.Add(4);
    // Does not compile.

    public MyClass()
    {
        ... // do some other stuff
    }
}
Customer c1 = new Customer()  
                  .FirstName("matt")
                  .LastName("lastname")
                  .Sex("male")
                  .Address("austria");
默认情况下,集合类中不提供此功能。为此,您必须实现自己版本的
IList

Lambda表达式是实现这一点的一种方法,如您的更新所示…

明白了:

IList<int> someList = new Func<List<int>>(() => { IList<int> l = new List<int>(); l.Add(2); l.Add(4); return l; })();

不,我不想填写每个构造函数的列表。我想在调用构造函数之前填充它。不幸的是,它不适用于
LinkedList
。。。一般来说(不仅仅是
List
),你知道怎么做吗?@Kjara
LinkedList
可以帮助你解决构造器的问题。:)您必须查看可以放置索引器的位置。通常这适用于每个
IList
子级。您的意思是
LinkedList(IEnumerable)
?这需要一个集合作为输入。我知道这是一个解决办法,但它需要不必要的内存。我可以对所有集合执行此操作。
K
ICollection myCollection=new K(new T[]{//put my elements here})
,但我不太满意。@Kjara我不确定您想要实现什么。
LinkedList
是一种特殊的集合,需要特殊处理<代码>IList是一件简单的事情,可以按索引器填充。
new Func<IList<int>>(...)
static Func<IList<int>> foo = () => { IList<int> l = new List<int>(); l.Add(2); l.Add(4); return l; };

IList<int> someList = foo();