【问题标题】:Exposing the indexer / default property via COM Interop通过 COM 互操作公开索引器/默认属性
【发布时间】:2008-11-18 16:23:35
【问题描述】:

我正在尝试用 C# 编写一个组件,供经典 ASP 使用,它允许我访问组件的索引器(也称为默认属性)。

例如:
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 互操作实现?

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

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

【问题讨论】:

    标签: c# collections asp-classic vbscript com-interop


    【解决方案1】:

    尝试将属性的 DispId 属性设置为 0,如MSDN documentation 中所述。

    【讨论】:

    • 谢谢,这让它工作了,但不是在这个[字符串键]上。我必须先将 DispId 应用于另一个属性。
    • 糟糕,似乎将 DispId 应用于索引器,例如this[string key],如果没有重载就可以工作。
    【解决方案2】:

    这是一个更好的解决方案,它使用索引器而不是 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[int index] 超载了索引器this[string name]

    【讨论】:

      【解决方案3】:

      感谢 Rob Walker 的提示,我通过将以下方法和属性添加到 MyCollection 使其工作:

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

      编辑:请参阅使用索引器的this better solution

      【讨论】:

        猜你喜欢
        • 2015-06-29
        • 1970-01-01
        • 2011-09-21
        • 2012-07-19
        • 2015-03-21
        • 1970-01-01
        • 1970-01-01
        • 2017-07-20
        • 1970-01-01
        相关资源
        最近更新 更多