问题描述
我想在程序中使用一些全局变量.我们有什么可以像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 常量时,我才会这样做,例如 PI .对于可以更改的参数,我更喜欢使用具有实例级值的类.我想您会需要这种灵活性来调整您的遗传算法,或一次使用多个参数集.这是做到这一点的一种方法(不可变的类):
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#中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!