Creating a COM indexed property from C#?
I am trying to mimic an old vb6 dll with a new .net one. The mimicry has to be perfect so that that callers don't know they are using a new .dll.
I have a curiousness though. In VB6 it has the following in the object library:
Property BankList(Index As Long) As String
But AFAIK property this can't be done in .net?
The closest I can get is creating a function that ex开发者_C百科hibits that behaviour but then the COM type goes from Property to Method.
Can anyone suggest how I would create that signature with a property?
You can adorn a regular indexer with the IndexerNameAttribute
attribute to expose a name for it to other languages. I'm not sure if this will achieve your goal, though.
Unfortunately, C# only supports the calling of named indexers as part of COM interop, there is no supported language way of implementing your own (i.e., a class can only have the default indexer with an IndexerNameAttribute
attribute).
You can create something that looks similar for C# callers by implementing a type with an indexer and then having a property of that type, but it doesn't map exactly to the VB6 equivalent you need.
See also: Using Indexers (C#)
Aside
As has been mentioned in other answers, while C# doesn't support named indexers, the .NET CLR and some other languages, such as VB.NET, do. You may want to consider changing your target language in order to get this feature.
According to http://blogs.msdn.com/b/kirillosenkov/archive/2009/10/20/indexed-properties-in-c-4-0.aspx you can't declare indexed properties in C#. However, in contrast to what some of the other answers state, the CLR does support them, and you can declare them in VB.NET.
Named parametrised properties cannot be created in C# (only a single default one, called this
is available).
There are a number of options:
- Change the interface (but that misses the point as client code will need to change).
- Use VB (.net), which can create such properties.
- Create an adapter in C++ to give complete control at a COM level.
The first would mean changing the interface, which breaks your requirement. The final option gives the most control but is significantly more complex (unless you already know C++ COM development). I would go with VB.NET.
Indexed properties are available in .Net/C#, but you can't name them:
public String this[long index]
{
get; set;
}
This makes a property called Item
but you don't use this name in C#:
myObj[1L];
If you want to call out to a named property in COM with C# 4.0, you can:
excel.Range["a"];
http://blogs.msdn.com/b/kirillosenkov/archive/2009/10/20/indexed-properties-in-c-4-0.aspx
Finally, if you want to have the index named for COM languages, you can use the IndexerNameAttribute to expose the indexer as a named property.
精彩评论