cod*_*nix 5 .net c# vb.net indexer language-interoperability
我可以在VB.NET中创建一个可以在C#中使用的类:
myObject.Objects[index].Prop = 1234;
Run Code Online (Sandbox Code Playgroud)
当然我可以创建一个返回数组的属性.但要求是索引是从1开始的,而不是从0开始的,所以这个方法必须以某种方式映射索引:
我试图这样做,但C#告诉我,我不能直接调用它:
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
Run Code Online (Sandbox Code Playgroud)
编辑 对不起,如果我有点不清楚:
C#只允许我调用这个方法
myObject.get_Objects(index).Prop = 1234
但不是
myObject.Objects[index].Prop = 1234;
这就是我想要实现的目标.
Bri*_*eon 13
语法是:
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
Run Code Online (Sandbox Code Playgroud)
该Default关键字是创建索引的魔力.不幸的是,C#不支持命名索引器.您将不得不创建一个自定义集合包装并返回它.
Public ReadOnly Property Objects As ICollection(Of ObjectData)
Get
Return New CollectionWrapper(parrObjectData)
End Get
End Property
Run Code Online (Sandbox Code Playgroud)
凡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
Run Code Online (Sandbox Code Playgroud)
您可以在 C# 中使用带有默认索引器的结构来伪造命名索引器:
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];
}
Run Code Online (Sandbox Code Playgroud)
如果这是一个好主意,那就是另一个问题了。
| 归档时间: |
|
| 查看次数: |
3040 次 |
| 最近记录: |