简体   繁体   中英

Properties of C# structs get unusable names in COM and VB6?

My C# code has a struct which I am exporting to COM. The properties of this struct are coming through with strange names that aren't even valid syntax in VB6, so they cannot be accessed.

Is there some way to get these to export with normal, usable names? Am I missing an attribute or something?


The format of the name in COM / VB6 is:

<original_name>k__BackingField

where only the original_name part was in my C# code.

I can only see these crazy property names in the VB6 Object Browser, Intellisense won't show it.

Here's the (slightly sanitized) code which is being built:

[Guid("....")]
[ComVisible(true)]
public struct MyStruct
{
    public string StringA { get; set; }
    public string StringB { get; set; }

    public MyStruct(string a, string b)
    {
        StringA = a;
        StringB = b;
    }

    ... // some other methods, no fields or properties
}

and for good measure here is the IDL that gets generated:

typedef [uuid(....), version(1.0), custom(xxxx, MyNamespace.MyStruct)]
struct tagMyStruct {
    LPSTR <StringA>k__BackingField;
    LPSTR <StringB>k__BackingField;
} MyStruct;

as shown by OleView. I can see it contains the same k__BackingField as noted above. So it seems these names are coming from the C# typelib export process.

public string StringA { get; set; } public string StringA { get; set; } is only a short form of the following

private string _stringA_BackingField;
public string StringA
{
  get { return _stringA_BackingField; }
  set { _stringA_BackingField = value; }
}

And since COM structs only contain fields and no properties you will see the backing field. Your example should work if you change the code to the following:

[Guid("....")]
[ComVisible(true)]
public struct MyStruct
{
    public string StringA;
    public string StringB;
}

By definition the struct type is a value type that is typically used to encapsulate small groups of related variables.

If you want to provide properties or methods you need to use a class . You find more information about structs here:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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