How to make a field read only outside class

2019-06-24 07:13发布

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?

4条回答
我命由我不由天
2楼-- · 2019-06-24 07:15

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楼-- · 2019-06-24 07:16

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.

查看更多
Evening l夕情丶
4楼-- · 2019-06-24 07:17

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
    }
}
查看更多
The star\"
5楼-- · 2019-06-24 07:28
public class Dog
{
    public int numberOfTeeth { get; private set; }

    public Dog() 
    {   
        countTeeth(); 
    }
}
查看更多
登录 后发表回答