Is named indexer property possible? [duplicate]

∥☆過路亽.° 提交于 2019-11-30 05:32:48

问题


Suppose I have an array or any other collection for that matter in class and a property which returns it like following:

public class Foo
{
    public IList<Bar> Bars{get;set;}
}

Now, may I write anything like this:

public Bar Bar[int index]
{
    get
    {
        //usual null and length check on Bars omitted for calarity
        return Bars[index];
    }
}

回答1:


Depending on what you're really looking for, it might already be done for you. If you're trying to use an indexer on the Bars collection, it's already done for you::

Foo myFoo = new Foo();
Bar myBar = myFoo.Bars[1];

Or if you're trying to get the following functionality:

Foo myFoo = new Foo();
Bar myBar = myFoo[1];

Then:

public Bar this[int index]
{
    get { return Bars[index]; }
}



回答2:


No - you can't write named indexers in C#. As of C# 4 you can consume them for COM objects, but you can't write them.

As you've noticed, however, foo.Bars[index] will do what you want anyway... this answer was mostly for the sake of future readers.

To elaborate: exposing a Bars property of some type that has an indexer achieves what you want, but you should consider how to expose it:

  • Do you want callers to be able to replace the collection with a different collection? (If not, make it a read-only property.)
  • Do you want callers to be able to modify the collection? If so, how? Just replacing items, or adding/removing them? Do you need any control over that? The answers to those questions would determine what type you want to expose - potentially a read-only collection, or a custom collection with extra validation.



回答3:


You can roll your own "named indexer" however. See

  • Why C# doesn't implement indexed properties?
  • Easy creation of properties that support indexing in C#



回答4:


You can use explicitly implemented interfaces, as shown here: Named indexed property in C#? (see the second way shown in that reply)




回答5:


public class NamedIndexProp
{
    private MainClass _Owner;
    public NamedIndexProp(MainClass Owner) { _Owner = Owner;
    public DataType this[IndexType ndx]
    {
        get { return _Owner.Getter(ndx); }
        set { _Owner.Setter(ndx, value); }
    }
}
public MainClass
{
    private NamedIndexProp _PropName;
    public MainClass()
    {
       _PropName = new NamedIndexProp(this);
    }
    public NamedIndexProp PropName { get { return _PropName; } }
    internal DataType getter(IndexType ndx)
    {
        return ...
    }
    internal void Setter(IndexType ndx, DataType value)
    {
       ... = value;
    }
}


来源:https://stackoverflow.com/questions/3293495/is-named-indexer-property-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!