Difference between Property and Field in C# 3.0+

2018-12-31 03:40发布

I realize that it seems to be a duplicate of What is the difference between a Field and a Property in C#? but my question has a slight difference (from my point of view):

Once I know that

  • I will not use my class with "techniques that only works on properties" and
  • I will not use validation code in the getter/setter.

Is there any difference (except the style/future development ones), like some type of control in setting the property?

Is there any additional difference between:

public string MyString { get; set; }

and

public string myString;

(I am aware that, that the first version requires C# 3.0 or above and that the compiler does create the private fields.)

10条回答
时光乱了年华
2楼-- · 2018-12-31 03:53

There is one other important difference between fields and properties.

When using WPF, you can only bind to public properties. Binding to a public field will not work. This is true even when not implementing INotifyPropertyChanged (even though you always should).

查看更多
人间绝色
3楼-- · 2018-12-31 03:55

The first one:

public string MyString {get; set; }

is a property; the second one ( public string MyString ) denotes a field.

The difference is, that certain techniques (ASP.NET databinding for instances), only works on properties, and not on fields. The same is true for XML Serialization: only properties are serialized, fields are not serialized.

查看更多
春风洒进眼中
4楼-- · 2018-12-31 04:02

Fields and properties look the same, but they are not. Properties are methods and as such there are certain things that are not supported for properties, and some things that may happen with properties but never in the case of fields.

Here's a list of differences:

  • Fields can be used as input to out/ref arguments. Properties can not.
  • A field will always yield the same result when called multiple times (if we leave out issues with multiple threads). A property such as DateTime.Now is not always equal to itself.
  • Properties may throw exceptions - fields will never do that.
  • Properties may have side effects or take a really long time to execute. Fields have no side effects and will always be as fast as can be expected for the given type.
  • Properties support different accessibility for getters/setters - fields do not (but fields can be made readonly)
  • When using reflection the properties and fields are treated as different MemberTypes so they are located differently (GetFields vs GetProperties for example)
  • The JIT Compiler may treat property access very differently compared to field access. It may however compile down to identical native code but the scope for difference is there.
查看更多
深知你不懂我心
5楼-- · 2018-12-31 04:03

Encapsulation.

In the second instance you've just defined a variable, in the first, there is a getter / setter around the variable. So if you decide you want to validate the variable at a later date - it will be a lot easier.

Plus they show up differently in Intellisense :)

Edit: Update for OPs updated question - if you want to ignore the other suggestions here, the other reason is that it's simply not good OO design. And if you don't have a very good reason for doing it, always choose a property over a public variable / field.

查看更多
看风景的人
6楼-- · 2018-12-31 04:08

Accessors are more than fields. Others have already pointed out several important differences, and I'm going to add one more.

Properties take part in interface classes. For example:

interface IPerson
{
    string FirstName { get; set; }
    string LastName { get; set; }
}

This interface can be satisfied in several ways. For example:

class Person: IPerson
{
    private string _name;
    public string FirstName
    {
        get
        {
            return _name ?? string.Empty;
        }
        set
        {
            if (value == null)
                throw new System.ArgumentNullException("value");
            _name = value;
        }
    }
    ...
}

In this implementation we are protecting both the Person class from getting into an invalid state, as well as the caller from getting null out from the unassigned property.

But we could push the design even further. For example, interface might not deal with the setter. It is quite legitimate to say that consumers of IPerson interface are only interested in getting the property, not in setting it:

interface IPerson
{
    string FirstName { get; }
    string LastName { get; }
}

Previous implementation of the Person class satisfies this interface. The fact that it lets the caller also set the properties is meaningless from the point of view of consumers (who consume IPerson). Additional functionality of the concrete implementation is taken into consideration by, for example, builder:

class PersonBuilder: IPersonBuilder
{
    IPerson BuildPerson(IContext context)
    {

        Person person = new Person();

        person.FirstName = context.GetFirstName();
        person.LastName = context.GetLastName();

        return person;

    }
}

...

void Consumer(IPersonBuilder builder, IContext context)
{
    IPerson person = builder.BuildPerson(context);
    Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
}

In this code, consumer doesn't know about property setters - it is not his business to know about it. Consumer only needs getters, and he gets getters from the interface, i.e. from the contract.

Another completely valid implementation of IPerson would be an immutable person class and a corresponding person factory:

class Person: IPerson
{
    public Person(string firstName, string lastName)
    {

        if (string.IsNullOrEmpty(firstName) || string.IsNullOrEmpty(lastName))
            throw new System.ArgumentException();

        this.FirstName = firstName;
        this.LastName = lastName;

    }

    public string FirstName { get; private set; }

    public string LastName { get; private set; }

}

...

class PersonFactory: IPersonFactory
{
    public IPerson CreatePerson(string firstName, string lastName)
    {
        return new Person(firstName, lastName);
    }
}
...
void Consumer(IPersonFactory factory)
{
    IPerson person = factory.CreatePerson("John", "Doe");
    Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
}

In this code sample consumer once again has no knowledge of filling the properties. Consumer only deals with getters and concrete implementation (and business logic behind it, like testing if name is empty) is left to the specialized classes - builders and factories. All these operations are utterly impossible with fields.

查看更多
萌妹纸的霸气范
7楼-- · 2018-12-31 04:09

A couple quick, obvious differences

  1. A property can have accessor keywords.

    public string MyString { get; private set; }
    
  2. A property can be overridden in descendents.

    public virtual string MyString { get; protected set; }
    
查看更多
登录 后发表回答