2008-11-18 74 views
4

我正在尝试在C#中编写一个组件,供经典ASP使用,该组件允许我访问组件的索引器(又名默认属性)。通过COM公开索引器/默认属性

例如:
C#组件:

public class MyCollection { 
    public string this[string key] { 
     get { /* return the value associated with key */ } 
    } 

    public void Add(string key, string value) { 
     /* add a new element */ 
    } 
} 

ASP消费者:

Dim collection 
Set collection = Server.CreateObject("MyCollection ") 
Call collection.Add("key", "value") 
Response.Write(collection("key")) ' should print "value" 

有我需要设置一个属性,我需要实现一个接口或者我需要做别的事吗?或者这不可能通过COM Interop?

目的是我试图为一些内置ASP对象(如Request)创建测试双打,这些对象使用这些默认属性(例如Request.QueryString("key"))使用集合。欢迎提供其他建议。

更新:我问一个后续问题:Why is the indexer on my .NET component not always accessible from VBScript?

回答

3

尝试设置属性的DISPID属性为0,如MSDN documentation描述。

+0

谢谢,这让它工作,但不是在这[字符串键]。在它工作之前,我必须将DispId应用到另一个属性。 – 2008-11-19 07:37:14

0

感谢Rob Walker的提示,我把它加入下面的方法工作,归因于MyCollection的:

[DispId(0)] 
public string Item(string key) { 
    return this[key]; 
} 

编辑:看到这个更好的解决方案,它使用一个索引。

0

这里是一个更好的解决方案,它使用一个索引,而不是Item方法:

public class MyCollection { 
    private NameValueCollection _collection; 

    [DispId(0)] 
    public string this[string name] { 
     get { return _collection[name]; } 
     set { _collection[name] = value; } 
    } 
} 

可以从ASP中使用,如:

Dim collection 
Set collection = Server.CreateObject("MyCollection") 
collection("key") = "value" 
Response.Write(collection("key")) ' should print "value" 

注:我不能得到这个工作之前是因为我已经超载索引器this[string name]this[int index]