Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 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 Answer

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...