How pass an decimal from c# to vb6 with Interop

谁都会走 提交于 2019-12-01 20:37:16

The error message is appropriate, decimal is not a valid interop type. It suffers from very poor standardization, the big chip bakers like Intel and AMD don't want to touch it with a ten foot pole. I can't remember VB6 anymore but this MSDN article brings the point home well:

At this time the Decimal data type can only be used within a Variant, that is, you cannot declare a variable to be of type Decimal. You can, however, create a Variant whose subtype is Decimal using the CDec function.

You declare a property as a variant by changing its type to object. I know that the .NET Decimal type is in fact compatible with the VB6 and VBA variant type, it is baked into oleauto.dll which is used both by the CLR and the VB6 and VBA runtime. Fix:

[ComVisible(true)]
public interface IExample {
    object ImportoDocumento { get; set; }
}

[ClassInterface(ClassInterfaceType.None)]
[ComVisible(true)]
public class Example : IExample {
    private decimal documento;
    public object ImportoDocumento {
        get { return documento; }
        set { documento = Convert.ToDecimal(value, null); }
    }
}

Note that you can play with the IFormatProvider argument of Convert.ToDecimal(). Matters when the VB6 code is apt to assign a string, not uncommon. You might also consider CultureInfo.InvariantCulture.NumberFormat.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!