سؤال

These 4 classes do the same but can someone explain why should you use one instead of theother?

public class MyClass
{
    public string MyString { get; set; }
}

public class MyClass
{
    public string MyString;
}

public class MyClass
{
    private string _mystring;
    public string MyString
    {
      get { return (string)GetValue(_mystring); }
      set { SetValue(_mystring, value); }
    }
}

public class MyClass
{
    private string _mystring;
    public string MyString
    {
        get { return _mystring; }
        set { _mystring = value; }
    }
}

I can interface any of them with

MyClass m=new MyClass();
m.MyString="test";

Is it personal coding preference or is there a reason for each?

هل كانت مفيدة؟

المحلول

All of your examples are effectively equivalent in practice, though if you implement as property set/get methods, you have the ability to intervene in the process, for example you could notify that a value was changed;

public class MyClass
{
    public event PropertyChangedHandler PropertyChanged;

    private string myString;
    public string MyString
    {
        get
        {
            return myString;
        }
        set 
        {
            // don't allow same value to be set 
            if (value == myString) return;
            myString = value;
            PropertyChanged(this, "MyString");
        }
    } 
}

Other examples might be; add validation logic, add security/authorisation before accepting a set call, return a composite value in a getter.

نصائح أخرى

In my humble opinion, the 1st, 3rd, and 4th are just different ways to declare a property of the class (with the get and set accessor). The 1st way is probably the fastest to declare a property, but with limited flexibility compared to the 3rd and 4th.

The 2nd function uses something different from a property, it has a public field, which is considered a bad practice. We should always use properties to access private members of the class.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top