开发者

c# - how do square brackets in a method declaration fit in with c#?

How do squa开发者_开发问答re brackets in a method declaration fit in with c#? That is I see when reading up on WPF validation one can use IDataErrorInfo with an example of the following.

public string this[string propertyName]

// Error handling takes place here.
public string this[string propertyName]  // <== IE HERE
{
  get
  // etc 
  }
}

I note MSDN says "Square brackets ([]) are used for arrays, indexers, and attributes. They can also be used with pointers." So is the above usage a pointer?


This is a standard feature of the C# language called an Indexer. Generally you would use these when writing your own collections, or similar types. Here is a brief (not real world) example.

public class Foo {
    private List<int> m_Numbers = new List<int>();

    public int this[int index] {
        get {
            return m_Numbers[index];
        }
        set {
            m_Numbers[index] = value;
        }
    }
}

class Program {
    static void Main() {
        Foo foo = new Foo();
        foo[0] = 1;
    }
}

There's a lot of cool things you can use indexers for if you are creative, it's a really neat feature of the language.


This is a declaration of an Indexer. It's analagous to array indexing. propertyName is a string which the method uses to index into some kind of collection. The method returns the corresponding string from the collection.

Of course, the method could do something else, but that's what the semantics mean.


That would be an indexer property. They're useful on custom collections:

public class MyCustomCollection
{
    List<MyObject> _list = new List<MyObject>();

    public string this[string name]
    {
        get { return _list.Single(o => o.Name == name)
                          .Select(o => o.Description);
    }

    public string this[int id]
    {
        get { return _list.Single(o => o.Id == id).Select(o => o.Description);
    }
}

And then you can use the collection like:

MyCollection col = new MyCollection();

// Fill the collection

string description = col["Name"];
string description2 = col[2];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜