C#中的全局变量 [英] Global variable in C#

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

问题描述

我想在程序中使用一些全局变量.我们有什么可以像C ++中的#define那样帮助直接定义全局变量的吗?

I want to use some global variables in my program. Do we have anything which could help directly define global variables as we have #define in C++.

例如:说我在C ++中具有以下提到的全局变量:

For Eg: Say I have the below mentioned global variables in C++:

#define CROSSOVER_RATE            0.7
#define MUTATION_RATE             0.001
#define POP_SIZE                  100        
#define CHROMO_LENGTH             300
#define GENE_LENGTH               4
#define MAX_ALLOWABLE_GENERATIONS   400

我希望在我的C#程序中将它们仅定义为全局变量.请让我知道我该怎么办?

I wish to define these in my C# program as global variables only. Please let me know how can I do it?

推荐答案

您可以在一个类中定义它们:

You can define them inside a class:

public static class Constants {
  public const double CrossoverRate = 0.7;
  ...
}

像这样使用它们:Constants.CrossoverRate.

但是,只有在它们是 really 常量时,我​​才会这样做,例如

But I'd only do that if they were really constant, like PI. For parameters that can change, I'd prefer using a class with instance-level values. I think you'll want this kind of flexibility to tune your genetic algorithm, or to use more than one parameter-set at once. This is one way to do it (immutable class):

public class GeneticAlgorithmParameters {

  public double CrossoverRate { get; private set; }
  ...

  public GenericAlgorithmParameters(double crossoverRate, ... others) {
    CrossoverRate = crossoverRate;
    ...
  }

}

现在,您将GeneticAlgorithmParameters的实例传递给您的GeneticAlgorithm类构造函数.

Now you pass an instance of GeneticAlgorithmParameters to your GeneticAlgorithm class constructor.

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

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