在 VB.NET 中创建可从 C# 使用的索引器 [英] Create Indexer in VB.NET which can be used from C#

查看:37
本文介绍了在 VB.NET 中创建可从 C# 使用的索引器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 VB.NET 中创建一个可以从 C# 中使用的类吗:

Can I create a class in VB.NET which can be used from C# like that:

myObject.Objects[index].Prop = 1234;

当然我可以创建一个返回数组的属性.但要求是索引是从 1 开始的,而不是从 0 开始的,所以这个方法必须以某种方式映射索引:

Sure I could create a property which returns an array. But the requirement is that the index is 1-based, not 0-based, so this method has to map the indices somehow:

我试图这样做,但 C# 告诉我我不能直接调用它:

I was trying to make it like that, but C# told me I cannot call this 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 was a bit unclear:

C# 只允许我像

myObject.get_Objects(index).Prop = 1234

但不是

myObject.Objects[index].Prop = 1234;

这就是我想要的.

推荐答案

您可以在 C# 中使用带有默认索引器的结构来伪造命名索引器:

You can fake named indexers in C# using a struct with a default indexer:

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

如果这是一个好主意是另一个问题.

If that's a good idea is a different question.

这篇关于在 VB.NET 中创建可从 C# 使用的索引器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆