Create an Indexer in VB.NET that can be used with C #

Can I create a class in VB.NET that can be used with C # as follows:

myObject.Objects[index].Prop = 1234;

Of course, I can create a property that returns an array. But the requirement is that the index is based on 1, not 0, so this method must somehow match the indices:

I tried to do it like this, but C # told me that I cannot call it directly:

   Public ReadOnly Property Objects(ByVal index As Integer) As ObjectData
        Get
            If (index = 0) Then
                Throw New ArgumentOutOfRangeException()
            End If
            Return parrObjectData(index)
        End Get
    End Property

EDIT Sorry if I'm a little unclear:

C # only allows me to call this method, for example

myObject.get_Objects(index).Prop = 1234

but not

myObject.Objects[index].Prop = 1234;

this is what I want to achieve.

+5
source share
4 answers

# :

public class ObjectData
{
}

public class MyClass
{
    private List<ObjectData> _objects=new List<ObjectData>();
    public ObjectsIndexer Objects{get{return new ObjectsIndexer(this);}}

    public struct ObjectsIndexer
    {
        private MyClass _instance;

        internal ObjectsIndexer(MyClass instance)
        {
            _instance=instance;
        }

        public ObjectData this[int index]
        {
            get
            {
                return _instance._objects[index-1];
            }
        }
    }
}

void Main()
{
        MyClass cls=new MyClass();
        ObjectData data=cls.Objects[1];
}

, .

+4

:

Default Public ReadOnly Property Item(ByVal index as Integer) As ObjectData
  Get
    If (index = 0) Then
      Throw New ArgumentOutOfRangeException()
    End If
    Return parrObjectData(index)
  End Get
End Property

Default - , . , # . .

Public ReadOnly Property Objects As ICollection(Of ObjectData)
  Get
    Return New CollectionWrapper(parrObjectData)
  End Get
End Property

CollectionWrapper :

Private Class CollectionWrapper
  Implements ICollection(Of ObjectData)

  Private m_Collection As ICollection(Of ObjectData)

  Public Sub New(ByVal collection As ICollection(Of ObjectData))
    m_Collection = collection
  End Sub

  Default Public ReadOnly Property Item(ByVal index as Integer) As ObjectData
    Get
      If (index = 0) Then
        Throw New ArgumentOutOfRangeException()
      End If
      Return m_Collection(index)
    End Get
  End Property

End Class
+13

# ( ), , (, VB), getter (get_MyProperty/set_MyProperty)

+1

0, , 1?

Return parrObjectData(index-1)
0

All Articles