Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

Private Accessor in C#

I'm a little confused about accessor's in C#. I assumed something like this could be done for private accessor's:

private string m_name =
{
    get { return m_name; } // Not sure if this is actually correct. Maybe use 'this'
    set { m_name = value } // Not even sure if this is correct
} 

I'm not sure if the code above is valid. I've not used accessors in C#.

Instead, documentation states to do this:

class Employee
{
     private string m_name;

     public string Name
     {
         get { return m_name; }
         protected set { m_name = value; }
      }
}

Why is this done, because from my perspective the user can still access the private m_name property via Name. Doesn't this defeat the point of private (or even protected) properties?

In the first example shouldn't the compiler know its private and thus create the methods behind the scenes (as I believe it does at compile time)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your first example will give you a StackOverflowException, you need to either use a separate member to store your data or use Auto Properties.

To answer your question, The reason this is done is to effectively make the property readonly to everyone outside of the class, but allow any code running inside the class to still set the property.

class Employee
{
     public Employee(string name)
     {
         Name = name;
     }

     private string m_name;

     public string Name
     {
         get { return m_name; }
         protected set { m_name = value; }
     }

     public void ChangeName(string name)
     {
         Name = name;
     }
}

public class Ceo : Employee
{
    public Ceo(string name) : base(name)
    {
    }

    public void VoteOut()
    {
         Name = Name + " (FIRED)";
    }
}


static class MainClass
{
    static void Main(string[] args)
    {
        var employee = new Employee("Scott Chamberlain");

        Console.WriteLine(employee.Name) //Displays Scott Chamberlain;

        //employee.Name = "James Jeffery"; //Has a complier error if uncommented because Name is not writeable to MainClass, only members of Employee can write to it.

        employee.ChangeName("James Jeffery");

        Console.WriteLine(employee.Name) //Displays James Jeffery;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...