将int的值声明为不可更改

时间:2013-01-02 23:55:17

标签: c# variables declaration

嘿我想要有类似的东西

int a=0;
a=5(be unchangeable);
a=3;
Console.WriteLine(a);//which will print 5 and not 3

所以基本上把变量声明为一个数字并让它变成最终且不可更改的,我试着四处寻找,但我只发现了一些工作为int的东西,而不是声明它的新值。

5 个答案:

答案 0 :(得分:6)

这不起作用吗?

const int a = 5;

请参阅const(C# reference)

答案 1 :(得分:3)

const int a = 0;
  

const关键字用于修改字段或本地的声明   变量。它指定字段或本地的值   变量是常量,这意味着它不能被修改。

Ref

答案 2 :(得分:3)

您需要const关键字。

const int a = 5;

来自MSDN

  

const关键字用于修改字段或局部变量的声明。它指定不能修改字段或局部变量的值。

编辑:你的要求听起来很奇怪而且没用。但如果你真的需要它,你将不得不创建一个自定义类型。我建议使用bool属性的类来说明它是否可变。

public class MyCustomInt
{
    public bool IsMutable { get; set; }

    private int _myInt;
    public int MyInt 
    { 
        get
        {
            return _myInt;
        } 
        set
        {
            if(IsMutable)
            {
                _myInt = value;
            }
        }
    }

    public MyCustomInt(int val)
    { 
        MyInt = val;
        IsMutable = true;
    }
}

然后当你使用它时:

MyCustomInt a = new MyCustomInt(0);
a.MyInt = 5;
a.IsMutable = false;
a.MyInt = 3; //Won't change here!
Console.WriteLine(a); //Prints 5 and not 3

我认为这就像你能得到的一样好。

答案 3 :(得分:3)

使用readonly

因为它可以被构造函数更改但不会再次更改。

public class MyClass {
 private readonly int a = 0;
 public MyClass(int a) {
  this.a = a;
 }

 public void DoSomethingWithA() {
   Console.WriteLine(this.a);
   //a = 5 // don't try this at home kids
 }
}

new MyClass(5).DoSomethingWithA();

A nice comparison between constreadonly

答案 4 :(得分:0)

您可以使用const关键字的常量。

const int a = 5;

但如果您这样做,则不允许您更改为其他值。

您还可以检查指针的使用:

int x = 5;
int y = 3;
int *ptr1 = &x; // point to x memory address
int *ptr2 = &y; // point to y memory address

Console.WriteLine(x); // print 5
Console.WriteLine(y); // print 3

Console.WriteLine((int)ptr1); // print 5
Console.WriteLine((int)ptr2); // print 3
Console.WriteLine(*ptr1); // print 5
Console.WriteLine(*ptr2); // print 3

* char标识指针,&指定内存地址。但是你应该注意指针,因为与引用类型不同,默认的垃圾收集机制不会跟踪指针类型。