轻松创建支持索引在C#中的属性 [英] Easy creation of properties that support indexing in C#

查看:237
本文介绍了轻松创建支持索引在C#中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中我发现索引属性非常有用的。例如:

In C# I find indexed properties extremely useful. For example:

var myObj = new MyClass();
myObj[42] = "hello"; 
Console.WriteLine(myObj[42]);



不过,据我所知是没有语法糖来支持自己支持索引字段(请纠正我,如果我错了)。例如:

However as far as I know there is no syntactic sugar to support fields that themselves support indexing (please correct me if I am wrong). For example:

var myObj = new MyClass();
myObj.field[42] = "hello"; 
Console.WriteLine(myObj.field[42]);



我需要这样做的原因是,我已经用我的分类的索引属性,但我有 GetNumX()的getX() SETX()功能如下:

public int NumTargetSlots {  
    get { return _Maker.NumRefs; }  
}
public ReferenceTarget GetTarget(int n) {
    return ReferenceTarget.Create(_Maker.GetReference(n));
}
public void SetTarget(int n, ReferenceTarget rt) {
    _Maker.ReplaceReference(n, rt._Target, true);
}



正如你可能会看到公开这些为一个可索引字段属性会更有意义。我可以写一个自定义的类来实现这一点,我想语法糖,但所有的样板代码只是似乎没有必要每次。

As you can probably see exposing these as one indexable field property would make more sense. I could write a custom class to achieve this every time I want the syntactic sugar but all of the boilerplate code just seem unnecessary.

所以我写了一个自定义的类来封装的样板,并可以很容易地创建一个可以被索引的属性。这样我可以添加如下新特性:

So I wrote a custom class to encapsulate the boilerplate and to make it easy to create properties that can be indexed . This way I can add a new property as follows:

public IndexedProperty<ReferenceTarget> TargetArray  {
    get { 
       return new IndexedProperty<int, ReferenceTarget>(
           (int n) => GetTarget(n), 
           (int n, ReferenceTarget rt) => SetTarget(n, rt));
       }
}

有关这个新IndexedProperty类的代码如下:

The code for this new IndexedProperty class looks like:

public class IndexedProperty<IndexT, ValueT>
{
    Action<IndexT, ValueT> setAction;
    Func<IndexT, ValueT> getFunc;

    public IndexedProperty(Func<IndexT, ValueT> getFunc, Action<IndexT, ValueT> setAction)
    {
        this.getFunc = getFunc;
        this.setAction = setAction;
    }

    public ValueT this[IndexT i]
    {
        get {
            return getFunc(i);
        }
        set {
            setAction(i, value);
        }
    }
}



所以我的问题是:< STRONG>有没有更好的方式来做到这一切?

好是具体的,有没有在C#中更地道的方式来创建一个可转位字段属性,如果没有我怎么能提高我的 IndexedProperty 类?

Well to be specific, is there a more idiomatic way in C# to create an indexable field property, and if not how could I improve my IndexedProperty class?

编辑:经过进一步研究,乔恩斯基特称这是一个的命名索引

After further research, Jon Skeet calls this a "named indexer".

推荐答案

好,该simpliest是有属性返回一个对象,它实现的IList

Well, the simpliest is to have the property return an object which implements IList.

请记住,只是因为它实现IList但这并不意味着它是一个集合本身,只是它实现某些方法。

Remember that just because it implements IList doesn't mean it's a collection itself, just that it implements certain methods.

这篇关于轻松创建支持索引在C#中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆