【问题标题】:Why C++ CLI indexed properties does not work in C#?为什么 C++ CLI 索引属性在 C# 中不起作用?
【发布时间】:2013-03-12 10:23:57
【问题描述】:

有两个项目,一个 C++ CLI 和另一个 C# 项目。
C# 项目中引用了 C++ CLI 程序集。

一切都很好,除了索引属性不起作用。
C++ CLI 代码:

property Nullable< int> PVarInt[System::String^] {
    Nullable<int> get(System::String^ inx){
    }
    void set(System::String^ inx, Nullable< int>  newx){
    }
}

C# 中的代码显示为两个 set 和 get 方法,如下所示:

get_PVarInt(..)
set_PVarInt(..)

这是一个错误吗?有解决办法吗?为什么会发生这种情况?

【问题讨论】:

  • > 使用这种调用机制,但很少不安全。 System.Diagnostics.Process 进程 = 新 System.Diagnostics.Process(); process.StartInfo.FileName = "App.exe"; process.StartInfo.Arguments = "arg1 arg2 arg3"; process.Start();
  • 我写了一篇关于我在将 VB.NET 应用程序转换为 C# 时创建的类的博客文章,它可能对你有用。 PropertyWrapper
  • @JensGranlund 这很有用,谢谢

标签: c# c++ .net visual-c++ c++-cli


【解决方案1】:

C# 不支持除this 属性之外的索引属性。

但是 .NET 框架确实如此,因此当使用支持该语言的语言创建索引属性时,它将在 C# 中显示为一个 get_Method 和一个 set_Method

【讨论】:

  • 有解决办法吗?
  • @Mahdi,这取决于您所说的修复。只要您正在访问由另一种语言创建的 C# 中的索引属性。但是您可以在 C# 中通过创建具有对象的属性并使用该对象索引该属性来伪造 C# 中的索引属性。
【解决方案2】:

C++/CLI 具有可从 C# 获得的索引属性: 示例:

public ref class ClassWithIndexer
{
private:
    array<int> ^x;
public:
    property int default[int]
    {
        int get(int index)
        {
            return x[index];
        }
        void set(int index, int value)
        {
            x[index] = value;
        }
    }
};

【讨论】:

  • 谢谢我已经在使用这种方式了。我已将我的属性移植到类中。
猜你喜欢
  • 1970-01-01
  • 2011-02-17
  • 2016-05-18
  • 1970-01-01
  • 1970-01-01
  • 2014-04-23
  • 1970-01-01
  • 2019-02-19
  • 2017-02-16
相关资源
最近更新 更多