2008-11-18 71 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]