开发者

Variable holding a number constantly without being able to edit the value [closed]

It's difficult to tell what is being开发者_运维知识库 asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

How do I make so a integer type of variable holds a number constantly through the whole time the game is running, without being able to edit the value inside?


You could use a constant:

public const int SomeValue = 123;

or a readonly instance field which could only be assigned in the constructor of the class:

public class Foo
{
    public readonly int SomeValue;
    public Foo()
    {
        SomeValue = 123;
    }
}

or you could use a static readonly field (which need to be initialized either in a static constructor or inline):

public static readonly int SomeValue = 123;

or you could use a property with a private setter allowing you to set the value only from inside the containing class:

public class Foo
{
    public int SomeValue { get; private set; }
    public Foo()
    {
        SomeValue = 123;
    }
}

or you could implement the Singleton pattern if you want this value to be initialized only once for the entire lifetime of the application.

So, yes, based on what exactly you are trying to achieve there are many ways to achieve it. Depending on the specific context some methods might be preferred than others.


You have a couple of choices here.

One is to use a constant.

 const float pi = 3.14f;
 const int r = 123;
 const string selectQuery = "SELECT * FROM [Products]";

Another is to use a readonly variable.

  public readonly int y = 25; 
  public readonly int z;
  public static readonly uint l1 = (uint) DateTime.Now.Ticks;

What's the difference? A const can only be initialized when it is declared. That is, the value is set when the variable is declared, and it cannot be changed.

A readonly field can be initialized when it is declared OR in a constructor. So, while a const field is a compile-time constant, the readonly field can be used for runtime constants.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜