实现 IEnumerable 的类并提供 public void Add(/* args */)函数可以像下面的例子一样初始化:

List<int> numbers = new List<int>{ 1, 2, 3 };

调用 Add(int)初始化 List<int> 后的函数 3x .

有没有办法为我自己的类明确定义这种行为?例如,我可以让初始化程序调用一个函数而不是适当的 Add() 吗?重载?

最佳答案

不,编译器需要一个名为 Add 的方法。使集合初始值设定项工作。这是在 C# 规范中定义的,不能更改:

 

 C# Language Specification - 7.5.10.3 Collection Initializers

The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or a compile-time error occurs. For each specified 
element in order, the collection initializer invokes an Add method on the target object with the expression list of the element initializer as argument list, applying normal overload 
resolution for each invocation. Thus, the collection object must contain an applicable Add method for each element initializer. [emphasis mine]

官方案例:

public class FullExample
    {
        class FormattedAddresses : IEnumerable<string>
        {
            private List<string> internalList = new List<string>();
            public IEnumerator<string> GetEnumerator() => internalList.GetEnumerator();

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => internalList.GetEnumerator();

            public void Add(string firstname, string lastname,
                string street, string city,
                string state, string zipcode) => internalList.Add(
                $@"{firstname} {lastname}
{street}
{city}, {state} {zipcode}"
                );
        }

        public static void Main()
        {
            FormattedAddresses addresses = new FormattedAddresses()
            {
                {"John", "Doe", "123 Street", "Topeka", "KS", "00000" },
                {"Jane", "Smith", "456 Street", "Topeka", "KS", "00000" }
            };

            Console.WriteLine("Address Entries:");

            foreach (string addressEntry in addresses)
            {
                Console.WriteLine("\r\n" + addressEntry);
            }
        }

        /*
         * Prints:

            Address Entries:

            John Doe
            123 Street
            Topeka, KS 00000

            Jane Smith
            456 Street
            Topeka, KS 00000
         */
    }

 

编程是个人爱好