Getter property with arguments

前端 未结 3 932
情深已故
情深已故 2020-12-29 20:43

I guess I\'ve seen it somewhere before, but now I can\'t remember nor find it. Is there a way to make a getter property with arguments?

I mean, as I can convert "

相关标签:
3条回答
  • 2020-12-29 21:25

    To answer the question: No, it is not possible, and as already pointed out, a getter with a parameter would look just like a method.

    The thing you are thinking about might be an indexed default property, which looks like this:

    class Test
    {
        public string this[int index] 
        {
            get { return index.ToString(); } 
        }
    }
    

    This allows you to index into an instance of Test, like this:

    Test t = new Test();
    string value = t[1];
    
    0 讨论(0)
  • 2020-12-29 21:26

    It is possible for a class object to reasonably-efficiently have something that behaves as a named indexed property getter by having a property return a struct which simply holds a private reference to the class object and includes an indexed property getter which chains to a method in the class. Such a single-item structure can be generated at basically no cost (it can likely fit in a register, and will be loaded with a value that's in another register; the JIT may even be able to recognize that the same register can be used for both purposes), so if using such a getter makes code more readable that's a substantial argument in favor.

    Unfortunately, the inability of struct members to indicate whether or not they modify the underlying structure makes it impossible to use the same approach for an indexed property setter. Even though it would be helpful it one could have have an OrderedCollection<T> with something like:

    struct ByIndexAccessor {
      OrderedCollection<T> owner;
      ByIndexAccessor(OrderedCollection<T> o) { owner = o; }
    
      T this[int index] {
        get { return owner.handleGet(index); }
        set { owner.handleSet(index, value); }
      }
    }
    ByIndexAccessor ByIndex {
      get {return new ByIndexAccessor(this); }
    }
    

    and say myCollection.ByIndex[3] = newThing;, C# would reject such code because it has no way of knowing that this particular indexed set implementation can safely be used on a read-only structure.

    0 讨论(0)
  • 2020-12-29 21:30

    Interestingly, having a property with parameter is possible in VB.NET, like this:

    Public ReadOnly Property oPair(param As String) As Result
      Get
         'some code depends on param
      End Get
    End Property
    

    It's not superior to a regular function, but sometimes it is nice to have such a possibility.

    0 讨论(0)
提交回复
热议问题