问题
I have the struct below which is being compiled for COM interop. I get the following build warning:
warning : Type library exporter warning processing 'MyNamespace.MyStruct.k__BackingField, MyAssemblyName'. Warning: The public struct contains one or more non-public fields that will be exported.
But I don't see what it is referring to - there are no non-public fields nor fields at all. Maybe the compiler is generating something I can't see? What does this warning mean, and what if anything can I do to clean it up?
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;
}
public MyStruct(MyStruct other)
{
StringA = other.StringA;
StringB = other.StringB;
}
public override bool Equals(object obj)
{
if (!(obj is MyStruct)) return false;
var other = (MyStruct)obj;
return
other.StringA == this.StringA &&
other.StringB == this.StringB;
}
public static bool operator ==(MyStructa, MyStructb) => a != null && a.Equals(b);
public static bool operator !=(MyStructa, MyStructb) => !(a == b);
public override int GetHashCode() => ToString().GetHashCode();
public override string ToString() => $"{StringA}-{StringB}";
}
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 generated by OleView. I can see it contains the same k__BackingField
as in the warning - but its not clear what this means.
回答1:
You are using auto-properties:
public string StringA { get; set; }
The compiler auto-generates a backing field for each of them. This is exactly what
MyNamespace.MyStruct.k__BackingField
is referring to.
You are getting the warning because exposing a private field could be unintended or could lead to security issues. It is up to the developer to verify if that is the case. In your specific example, there would be no breach of encapsulation so it's fine to ignore the warning or suppress it. See also the official documentation on this from MSDN:
When to suppress warnings
It is safe to suppress a warning from this rule if public exposure of the field is acceptable.
来源:https://stackoverflow.com/questions/57827736/the-public-struct-contains-one-or-more-non-public-fields-that-will-be-exported