静态变量相关查询C# [英] Static variable related query c#

查看:46
本文介绍了静态变量相关查询C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在.net 2.0中有一个C#类,在其中我想使用变量(静态int),其值在一个静态方法中设置,而该变量在另一种静态方法中使用.

该变量的值根据某些条件而变化.
该变量必须只有两个值0,1,如果是,则为true和false.

我在该类中声明了一个静态的int类型变量,该变量是全局的,并且两种方法都可以使用它,但是我遇到了一个异常对象不是对对象的引用".

同样,一旦分配的值将不会在以后的分配中更改.

Hi,

I have a C# class in .net 2.0 in which I want to use the variable(static int) whose values is set in one method which is static and that variable is used in another static method.

The value of that variable changes according to some condition.
That variable must have only two values 0,1 from if else for true and false.

I have declared a static int type variable in that class which is global and both methods can use that, but I got an exception ''object is not reference to object''.

Also value once assign will not change in future assignment.

thanks.

推荐答案

未通过对象实例引用的静态变量.

例如, public class Car{ public static int noOfWheels{get; set;} } 将由 Car.noOfWheels=4; 而不是 Car car=new Car(); car.noOfWheels=4;获取或设置.后来抛出异常
Static variables not referenced through an object instance.

For example public class Car{ public static int noOfWheels{get; set;} } will be get or set by Car.noOfWheels=4; and not by Car car=new Car(); car.noOfWheels=4;. The later throw exception


为什么没有人只是说:

最好的问候
Espen Harlinn
Why didn''t somebody just say: yes

Best regards
Espen Harlinn


配菜:如果您只需要一些值0或1的类型,则应该这样做:

A side dish: if you need some type with values 0 or 1 only, this is what you should do:

enum Discrete : byte { Low = 0, Hight = 1, } //for example



它将强制在编译时编写正确的代码,但不会在运行时阻止其他值(事实也可以从中受益).


为什么不布尔?有重要的应用程序.这是例子.想象一下使用或不使用某些特殊因子的数值计算.该怎么办?使用"if (useSpecialFactor) //..."? h!外观:



It will force writing correct code at compile time but won''t prevent other values during run-time (the fact which can be used to the benefit as well).


Why not boolean? There are important applications for that. Here is the example. Imagine a numeric calculation using or not using certain special factor. What to do? Using "if (useSpecialFactor) //..."? Nah! Look:

enum SpecialFactorUse { Ignore = 0, Use = 1, } 
//...
double Calculate(SpecialFactorUse specialFactorUse /* */) {
   //...
   return mainFactor + specialFactor * (int)specialFactorUse;
}

//...

enum Direction { Left = -1, StayHere = 0, Right = +1, } 
//...
Direction direction = getNewDirection(currentDirection, arrowKeys);
//...
double newPosition = currentPosition + step * (int)direction;



—SA



—SA


这篇关于静态变量相关查询C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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