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

“this”关键字作为属性

  •  16
  • viky  · 技术社区  · 14 年前

    我很清楚,但这对我来说很奇怪。在一些旧程序中,我看到了以下代码:

    public MyType this[string name]
    {
        ......some code that finally return instance of MyType
    }
    

    4 回复  |  直到 7 年前
        1
  •  32
  •   Andrew Bezzub    14 年前

    它是 indexer

    class MyClass
    {
        Dictionary<string, MyType> collection;
        public MyType this[string name]
        {
            get { return collection[name]; }
            set { collection[name] = value; }
        }
    }
    
    // Getting data from indexer.
    MyClass myClass = ...
    MyType myType = myClass["myKey"];
    
    // Setting data with indexer.
    MyType anotherMyType = ...
    myClass["myAnotherKey"] = anotherMyType;
    
        2
  •  7
  •   Reed Copsey    14 年前

    这是一个 Indexer Property . 它允许您通过索引直接“访问”类,就像访问数组、列表或字典一样。

    在你的情况下,你可以有这样的东西:

    public class MyTypes
    {
        public MyType this[string name]
        {
            get {
                switch(name) {
                     case "Type1":
                          return new MyType("Type1");
                     case "Type2":
                          return new MySubType();
                // ...
                }
            }
        }
    }
    

    你就可以像这样使用它:

    MyTypes myTypes = new MyTypes();
    MyType type = myTypes["Type1"];
    
        3
  •  2
  •   Paul Turner    14 年前

    索引器 . 这允许像数组一样访问类。

    myInstance[0] = val;
    

    您可以在MSDN文章中找到更多关于索引器的信息 Indexers (C# Programming Guide) .

        4
  •  0
  •   Peter Mortensen Len Greski    7 年前

    它是一个索引器,通常用作集合类型类。

    看一看 Using Indexers (C# Programming Guide) .