How to make a field read only outside class

2019-06-24 07:22发布

问题:

I have the following class (example):

public class Dog
{
    int numberOfTeeth;

    public Dog() 
    { 
        countTeeth(); 
    }

    private void countTeeth()
    {
        this.numberOfTeeth = 5; //this dog has seen better days, apparently
    }

}

After I create the dog object, it should have the number of teeth calculated. I'd like to be able to access that value without being able to modify it outside the class itself.

Dog d = new Dog();
int dogTeeth = d.numberOfTeeth; //this should be possible
d.numberOfTeeth = 10; //this should not

However, I can't figure out which access modifier will let me do this. I've tried all of the following:

If I make numberOfTeeth private, I cannot access it.
If I make numberOfTeeth protected internal, I can change this value outside the class.
If I make numberOfTeeth internal, I can change this value outside the class.
If I make numberOfTeeth protected, I cannot access it.
If I make numberOfTeeth public, I can change this value outside the class.

I also tried making it readonly but then was unable to set it outside the constructor.

Is there any access modifier which will allow me to do this? Or is there some other method of accomplishing this protection?

回答1:

Create a property with a private setter:

public int NumberOfTeeth
{
 get; private set;
}

Notice I changed it to Pascal Case to match most .NET style standards.



回答2:

You can't do that. You can make the field read-only and make a method that returns its value. You can also make an auto-property with a public getter and a protected setter:

public int NumberOfTeeth { get; protected set; }


回答3:

public class Dog
{
    public int numberOfTeeth { get; private set; }

    public Dog() 
    {   
        countTeeth(); 
    }
}


回答4:

You should make the field private and create a read-only (no setter) public property:

public class Dog
{
    private int numberOfTeeth;
    public int NumberOfTeeth {get {return numberOfTeeth;}}

    public Dog() 
    { 
        countTeeth(); 
    }

    private void countTeeth()
    {
        this.numberOfTeeth = 5; //this dog has seen better days, apparently
    }
}