質問

I know properties have some advantages, but if you think you won't need a property, what's the harm in making it a public instance?

People say that changing the public field to a property will break code if you try to do it later on but in my experience changing it to a property breaks nothing.

役に立ちましたか?

解決

I think that people mean that it breaks ABI (binary) compatibility, not the API (source) compatibility.

Although the syntax is identical, behind the scenes, access to properties and access to member variables are compiled differently.

That said, if your variable/property is not to be used from an assembly that you yourself do not compile, then there is no harm in changing it. But if it is part of a public interface, then it is better to make it a property, so that you will not regret it in the future.

他のヒント

It's about maintaining both binary and source compatibility. Some time in the future you may decide to make logic of assigning values more complex and to change fields to properties. This is where the problems emerge.

  1. Public fields can be used as out and ref parameters. Properties cannot. This will produce uncompilable code.

  2. Different Reflection methods are used to access fields and properties. That means any code that gets or sets values using Reflection will break, and you'll know about it only in run time.

  3. Different IL operators are used to access fields and properties. That means cross-assembly compatibility is broken when fields are changed to properties and only one assembly is recompiled. This will make your program fail at run time.

I concour with you, if the property is just a wrapper on the field. And the guys at Coding Horror looks like having our same opinion, I find very funny that frightened icon they use :) http://www.codinghorror.com/blog/2006/08/properties-vs-public-variables.html

A simple program.

Here I am adding two properties and one variables. We can use properties as per our decision. But I prefer to use properties because it helps to implement some bussiness validation and can hide the business logic form calling party.

class Program
    {
        static void Main(string[] args)
        {
            Human h = new Human();
            h.FirstName = "Test";
            h.LastName = "User";
            Console.WriteLine(h.FullName);
            Console.Read();
        }
    }
    class Human
    {
        public string FullName { get { return FirstName + " " + LastName; } }
        public string FirstName;//{ get; set; }
        public string LastName;//{ get; set; }

    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top