【问题标题】:cli interface with value type as return and C# interface implementation以值类型为返回值的 cli 接口和 C# 接口实现
【发布时间】:2013-09-19 12:19:18
【问题描述】:

我有 1. 声明接口(InterfaceCLI)和实现值类型(PointD)的CLI库 2. 带有实现 1 接口的类 (PointD) 的 C# 库

问题是 C# 上奇怪的接口实现。它需要这样的代码 公共值类型 GetPoint() 而不是 public PointD GetPoint()

示例代码 CLI:

public value struct PointD
//public ref class PointD
{
public:
    PointD(double x, double y);
    // Some stuff
};

public interface class InterfaceCLI
{
public:
    double Foo();
    PointD^ GetPoint();
};

示例代码 C#:

public class Class1 : InterfaceCLI
{
    public double Foo()
    {
        PointD x=new PointD( 1.0 , 2.7 );
        return x.Y;
    }

    public ValueType GetPoint()
    {
        throw new NotImplementedException();
    }

    /*
    public PointD GetPoint()
    {
        throw new NotImplementedException();
    }
     */
}

为什么在 Class1 类中需要 ValueType 而不是 PointD?!

【问题讨论】:

    标签: c# interface c++-cli value-type


    【解决方案1】:
    PointD^ GetPoint();
    

    值类型不是引用类型。所以你应该在这里使用 ^ 帽子。不幸的是,这种语法在 C++/CLI 中是允许的,它变成了一个装箱的值。很浪费。在 C# 中没有直接的等价物,除了你发现的用 ValueType 模拟它。

    摘下帽子来解决你的问题。

    【讨论】:

    • 非常感谢。问题已经解决了。在我看来,我必须将 PointD% 用于值类型。为什么在这种情况下我不应该使用 PointD%?
    • 这意味着完全不同的东西,用于通过引用传递函数参数。任何 C++/CLI 入门书籍都会告诉你这一点。
    猜你喜欢
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    相关资源
    最近更新 更多