如何使字段在课外只读 [英] How to make a field read only outside class

查看:72
本文介绍了如何使字段在课外只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程(示例):

 公共课程狗
{
int numberOfTeeth ;

public Dog()
{
countTeeth();
}

private void countTeeth()
{
this.numberOfTeeth = 5; //这只狗的日子更好,显然
}

}

创建狗对象后,应该计算出牙齿的数量。我希望能够访问该值,而不必在类本身之外进行修改。

  Dog d = new Dog(); 
int dogTeeth = d.numberOfTeeth; //这应该是可能的
d.numberOfTeeth = 10; //这不应该

但是,我不知道哪个访问修饰符会让我这样做。我尝试了以下所有操作:



如果我将 numberOfTeeth private ,我无法访问它。

如果我使 numberOfTeeth 受保护的内部,则可以在类外更改此值。 br />
如果我创建 numberOfTeeth 内部,则可以在类外更改此值。

如果我使 numberOfTeeth 受保护,则无法访问它。

如果我使 numberOfTeeth 公开,我可以在课堂外更改此值。



我也尝试将其设置为只读,但随后无法在构造函数外部进行设置。



是否有任何访问修饰符可以使我执行此操作?还是有其他实现此保护的方法?

解决方案

使用私有设置器创建属性:

  public int NumberOfTeeth 
{
get;私人套装;
}

注意,我将其更改为Pascal Case以匹配大多数.NET样式标准。 / p>

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?

解决方案

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.

这篇关于如何使字段在课外只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆