简体   繁体   English

如何使用Interop将c#中的小数传递给vb6

[英]How pass an decimal from c# to vb6 with Interop

I have an interop c# class with a property: 我有一个带有属性的interop c#类:

decimal ImportoDocumento {  get; set; }

if i try to access to this property from vb6 a receive an error: 如果我尝试从vb6访问此属性,则会收到错误:

Compiler error: Function or interface marked as restricted or the function uses an automation type not supported in visual basic. 编译器错误:标记为受限制的函数或接口,或者函数使用visual basic中不支持的自动化类型。

So i found this partial solution: 所以我找到了这个部分解决方案

decimal ImportoDocumento { [return: MarshalAs(UnmanagedType.Currency)] get; [param: MarshalAs(UnmanagedType.Currency)] set; }

but currency supports numbers with max 4 decimals. 但货币支持最多4位小数的数字。 i have numbers with 6 decimals too. 我的数字也是6位小数。

How can i do? 我能怎么做?

The error message is appropriate, decimal is not a valid interop type. 错误消息是合适的, decimal不是有效的互操作类型。 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. 它的标准化程度非常差,像英特尔和AMD这样的大芯片面包师不想用10英尺的杆子触摸它。 I can't remember VB6 anymore but this MSDN article brings the point home well: 我不记得VB6了,但这篇MSDN文章带来了好点:

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. 此时,Decimal数据类型只能在Variant中使用,也就是说,您不能将变量声明为Decimal类型。 You can, however, create a Variant whose subtype is Decimal using the CDec function. 但是,您可以使用CDec函数创建其子类型为Decimal的Variant。

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. 我知道.NET Decimal类型实际上与VB6和VBA变体类型兼容,它被烘焙到oleauto.dll中,CLR和VB6以及VBA运行时都使用它。 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(). 请注意,您可以使用Convert.ToDecimal()的IFormatProvider参数。 Matters when the VB6 code is apt to assign a string, not uncommon. VB6代码易于分配字符串时很重要,并非罕见。 You might also consider CultureInfo.InvariantCulture.NumberFormat. 您可能还会考虑CultureInfo.InvariantCulture.NumberFormat。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM