2015-12-20 14 views
6

私のクラスに初期化するコレクションを追加しようとしています。私はここで初期化子について読む:https://msdn.microsoft.com/en-us/library/bb384062.aspx#Anchor_2自分のクラスでコレクション初期化子を使用

私は私のパズルの重要な一部引用します:

Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable or a class with an Add extension method.

[OK]を、私は言葉またはに強調したいです。私はそれを読むと、私はメソッドを追加してクラスを作ることができるはずです、そして、コレクション初期化子はこのクラスで動作するでしょうか?これはそうではないようです。私が注目したことの一つは、実際にはAddメソッドを追加するということでした。だから私は拡張メソッドとして追加を作成しようとしましたが、役に立たない。ここで

は、私はそれが動作しませんしようとした小さなサンプルです:

public class PropertySpecificationCollection 
{ 
    private List<PropertySpecification> _internalArr; 
    public void Add(PropertySpecification item) 
    { 
     _internalArr.Add(item); 
    } 
} 

は私以外の解釈を引用対象ですか?私はそれを何度も何度も読んでいたが、他の方法でそれを解釈できるかどうかを見たが、失敗した。

私はそれを間違って解釈していますか?MSDNのコレクション初期化子の説明に何か不足していますか、エラーがありますか?

+0

'PropertySpecificationCollection'のインスタンスを作成してコンストラクタでコレクションを初期化するとどうなりますか? –

+2

これはドキュメントのエラーのように見えます。あなたは 'IEnumerable'を実装する必要があり、適切な' Add'メソッドが必要です。 – Lee

+0

http://stackoverflow.com/questions/2495791/custom-collection-initializers – Mino

答えて

4

「and」ではなく、「or」である必要があります。

コレクション初期化子がC# language specificationに記載されており、セクション7.6.10.3コレクション初期化子:

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.

それははっきりコレクションはAdd方法が必要IEnumerableを実装しなければならないと述べています。 Addメソッドへの呼び出しは、通常のオーバーロード解決プロセスを使用して解決されるため、拡張メソッド、汎用メソッドなどとなります。

+0

ありがとうございます。引用に加えて、C#言語仕様のセクションへのリンクを提供できますか? – Inrego

+0

@Inregoこれは.docxとしてのみ利用可能です。私はダウンロードサイトをリンクしました。 –

+0

@Jakobありがとうございます。私はウェブ検索でそれを見つけられないのも不思議ではありません。 – Inrego

関連する問題