代码之家  ›  专栏  ›  技术社区  ›  cdiggins

轻松创建支持C索引的属性#

  •  26
  • cdiggins  · 技术社区  · 16 年前

    在C#我发现 indexed properties

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

    然而,据我所知,没有语法糖来支持字段本身支持索引(请纠正我,如果我错了)。例如:

    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);
    }
    

    正如您可能看到的,将这些属性作为一个可转位字段属性公开将更有意义。每次我需要语法糖时,我都可以编写一个自定义类来实现这一点,但所有的样板代码似乎都是不必要的。

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

    此新IndexedProperty类的代码如下所示:

    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);
            }
        }
    }
    

    所以我的问题是: 有没有更好的方法来完成这一切

    IndexedProperty 上课?

    编辑: 经过进一步研究,乔恩·斯凯特称之为 named indexer ".

    7 回复  |  直到 9 年前
        1
  •  15
  •   Brian MacKay    7 年前

    我发现你的想法很有用,所以我扩展了它。从技术上讲,这可能不是一个正确的答案,因为我不确定它是否完全回答了您的问题,但我认为它可能对来这里寻找属性索引器的人有用。

    首先,我需要能够支持get only和set only属性,因此我对这些场景的代码做了一点小小的修改:

    获取并设置 (非常微小的变化):

    public class IndexedProperty<TIndex, TValue>
    {
        readonly Action<TIndex, TValue> SetAction;
        readonly Func<TIndex, TValue> GetFunc;
    
        public IndexedProperty(Func<TIndex, TValue> getFunc, Action<TIndex, TValue> setAction)
        {
            this.GetFunc = getFunc;
            this.SetAction = setAction;
        }
    
        public TValue this[TIndex i]
        {
            get
            {
                return GetFunc(i);
            }
            set
            {
                SetAction(i, value);
            }
        }
    }
    

    public class ReadOnlyIndexedProperty<TIndex, TValue>
    {
        readonly Func<TIndex, TValue> GetFunc;
    
        public ReadOnlyIndexedProperty(Func<TIndex, TValue> getFunc)
        {
            this.GetFunc = getFunc;
        }
    
        public TValue this[TIndex i]
        {
            get
            {
                return GetFunc(i);
            }
        }
    }
    

    public class WriteOnlyIndexedProperty<TIndex, TValue>
    {
        readonly Action<TIndex, TValue> SetAction;
    
        public WriteOnlyIndexedProperty(Action<TIndex, TValue> setAction)
        {
            this.SetAction = setAction;
        }
    
        public TValue this[TIndex i]
        {
            set 
            {
                SetAction(i, value);
            }
        }
    }
    

    例子

    下面是一个简单的用法示例。我从集合继承并创建一个命名索引器,Jon Skeet称之为索引器。本示例旨在简单而不实用:

    public class ExampleCollection<T> : Collection<T>
    {
        public IndexedProperty<int, T> ExampleProperty
        {
            get
            {
                return new IndexedProperty<int, T>(GetIndex, SetIndex);
            }
        }
    
        private T GetIndex(int index)
        {
            return this[index];
        }
        private void SetIndex(int index, T value)
        {
            this[index] = value;
        }
    }
    

    野外采集实例

    这个仓促构建的单元测试展示了当您在项目中对collection进行示例时它的外观:

    [TestClass]
    public class IndexPropertyTests
    {
        [TestMethod]
        public void IndexPropertyTest()
        {
            var MyExample = new ExampleCollection<string>();
            MyExample.Add("a");
            MyExample.Add("b");
    
            Assert.IsTrue(MyExample.ExampleProperty[0] == "a");
            Assert.IsTrue(MyExample.ExampleProperty[1] == "b");
    
            MyExample.ExampleProperty[0] = "c";
    
            Assert.IsTrue(MyExample.ExampleProperty[0] == "c");
    
        }
    }
    

    最后,如果要使用“仅获取”和“仅设置”版本,则如下所示:

        public ReadOnlyIndexedProperty<int, T> ExampleProperty
        {
            get
            {
                return new ReadOnlyIndexedProperty<int, T>(GetIndex);
            }
        }
    

    或:

        public WriteOnlyIndexedProperty<int, T> ExampleProperty
        {
            get
            {
                return new WriteOnlyIndexedProperty<int, T>(SetIndex);
            }
        }
    

        2
  •  9
  •   James Curran    16 年前

    最简单的方法是让属性返回一个实现 IList

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

        3
  •  7
  •   quentin-starin    16 年前

    public interface IIndexed<IndexT, ValueT>
    {
        ValueT this[IndexT i] { get; set; }
    }
    

    对于常见的情况,我将使用您在原始问题中输入的类(它将实现这个接口)。

        4
  •  5
  •   Mark H    16 年前

    这个 this[] C#中的索引器只是其中一个的特定实例,它被重命名为 Item 当你构建你的应用程序时。C#编译器只知道如何读取这个,因此如果您编写一个名为 Target ... get_Target(int) void set_Target(int, ...) 方法。烂透了。

        5
  •  3
  •   Community Mohan Dere    9 年前

    有关列表和数组的更多信息,请查看: Which is better to use array or List<>?

    编辑:

    MSDN有一篇关于索引属性的文章,你可能想看看。似乎并不复杂只是乏味。

    http://msdn.microsoft.com/en-us/library/aa288464(VS.71).aspx

    How do I override List<T>'s Add method in C#?

    编辑2: 类似于第一篇文章

    为什么不在类中有一个隐藏的list对象,然后创建自己的方法来获取数据呢。这样就看不到Add和Remove,并且列表已经被索引。

    http://msdn.microsoft.com/en-us/library/146h6tk5.aspx

    class Test
        {
            private List<T> index;
            public T this[string name]{ get; set; }
            public T this[int i]
            {
                get
                {
                    return index[i];
                }
                set
                {
                    index[i] = value;
                }
            }
        }
    
        6
  •  2
  •   damichab    11 年前

    经过一些研究,我想出了一个稍微不同的解决方案,更适合我的需要。这个例子是有点捏造,但它确实适合我需要它来适应它。

    用法:

    MyClass MC = new MyClass();
    int x = MC.IntProperty[5];
    

    以及使其工作的代码:

    public class MyClass
    {
        public readonly IntIndexing IntProperty;
    
        public MyClass()
        {
            IntProperty = new IntIndexing(this);
        }
    
        private int GetInt(int index)
        {
            switch (index)
            {
                case 1:
                    return 56;
                case 2:
                    return 47;
                case 3:
                    return 88;
                case 4:
                    return 12;
                case 5:
                    return 32;
                default:
                    return -1;
            }
        }
    
        public class IntIndexing
        {
            private MyClass MC;
    
            internal IntIndexing(MyClass mc)
            {
                MC = mc;
            }
    
            public int this[int index]
            {
                get { return MC.GetInt(index); }
            }
        }
    }