C#可以通过接口中的"索引器"和
get_Item
来实现。这是因为在IL编译期间生成属性/索引器getter和setter的方式。以下是
CLI规范中的描述:
I.10.4 命名模式
对于属性:
通过决定getter方法返回的类型和getter参数的类型(如果有)。然后,创建两个基于属性名称和这些类型的方法。在下面的示例中,我们定义了两个属性:Name不需要参数并返回System.String,而Item需要一个System.Object参数并返回System.Object。Item被称为索引属性,意味着它需要参数,因此可以像数组索引一样出现在用户面前。
PropertyGet, used to read the value of the property
Pattern: <PropType> get_<PropName> (<Indices>)
Example: System.String get_Name ();
Example: System.Object get_Item (System.Object key);
PropertySet, used to modify the value of the property
Pattern: void set_<PropName> (<Indices>, <PropType>)
Example: void set_Name (System.String name);
Example: void set_Item (System.Object key, System.Object value);
因此,您应该能够通过实现一些类似以下内容的索引器来满足条件:
public class ManagedEspritToolbar : Esprit.Toolbar
{
public ToolbarControl get_Item(int index) => Toolbar[index];
}
为了测试这个,您可以在VB.NET中创建一个简单的界面:
Public Interface IVBNetInterface
Property Item(index As Integer) As String
End Interface
然后在C#中的一个新类中实现该接口。注意,当允许IDE自动实现接口时,它默认为get_Item/set_Item
访问器:
public class CSharpClass : IVBNetInterface
{
public string get_Item(int index)
{
throw new NotImplementedException();
}
public void set_Item(int index, string Value)
{
throw new NotImplementedException();
}
}
阅读接口生成的IL代码可以证实这种行为:
![enter image description here](https://istack.dev59.com/1uxlv.webp)
VB.NET 的默认属性是什么?
在 VB.NET 中,有一个 Default
属性修饰符,它本质上是在类上声明索引器的机制:
Public Interface IVBNetInterface
Default Property Item(index As Integer) As String
End Interface
当VB.NET类/接口正确实现时,标准的C#
this[int]
索引实现将会起作用。因此,
get_Item
的解决方法
只有在目标索引属性未正确应用默认属性时才是必要的。请注意,一旦应用了该属性,调查IL代码时会添加
System.Reflection.DefaultMemberAttribute
属性。
![enter image description here](https://istack.dev59.com/sOCgS.webp)
提高使用效率:
为了规避底层类/接口没有使用Default
修饰符的问题,您可以显式实现接口索引器,这样可以在类上公开传统的C#风格的索引器:
public class CSharpClass : IVBNetInterface
{
public string this[int index]
{
get => throw new NotImplementedException();
set => throw new NotImplementedException();
}
#region IVBNetInterface
string IVBNetInterface.get_Item(int index) => this[index];
void IVBNetInterface.set_Item(int index, string value) => this[index] = value;
#endregion
}
如果您希望通过典型索引器推断类的使用方式,同时仍满足基础Interface.Item要求,则这可能是首选方法。
this[]
的返回类型是 'ToolBarControl' 吗? - NeilIToolBar
中Item[int]
定义的附加编辑和截图。 - Still.Tony