Why are public fields and properties interchangeab

2020-07-13 08:04发布

问题:

In the day job, I work on a VB6 (I know, but don't mock the afflicted...) application that uses a number of libraries we have written (also in the ever illustrious VB6). One of these supporting libraries had a load of private members exposed via public properties, and I was asked to remove the properties, and promote the private member variables into public fields with the same name as the original properties.

Now, I'm no COM expert, but I was under the impression that each and every exposed item on a class gets it's own GUID. Since we would be going from a situation where each value went from 2 Guids (Property Get and Property Let) to one where they only used the one (the public field), I was expecting this to break binary compatibility - but it seems it hasn't done that.

Can anyone explain why?

回答1:

I think it's a bit more subtle than that. You get a GUID for the COM interface (not each individual field/method). As I understand it the binary compatibility attempts to work out if the interface your currently compiling is backwards compatible with a reference version of your DLL (assuming you have one) and only changes the GUID if they are not compatible.

I'm therefore also surprised that it has decided removing all the get/set methods is compatible :/



回答2:

No, it hasn't broken compatibility because it hasn't removed the property get and property let methods. It's just that the compiler is now writing them for you.

Isn't this one of the few areas where VB6 is arguably better than .Net?

  • In .Net public fields behave differently to public properties, and this makes some refactorings difficult and causes confusion.
  • In VB6 public fields behave exactly like public properties, which is why it's possible to switch without affecting binary compatibility. Behind the scenes, the compiler generates property get and set routines for public fields. In a sense VB6 has automatically implemented properties (now advertised as a "new feature" in VB10)...