[英]Global variable in C#
我想在我的程序中使用一些全局變量。 我們有什么可以幫助直接定義全局變量,因為我們在C ++中有#define。
例如:假設我在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#程序中將它們定義為全局變量。 請讓我知道我該怎么辦?
您可以在類中定義它們:
public static class Constants {
public const double CrossoverRate = 0.7;
...
}
像這樣使用它們: Constants.CrossoverRate
。
但是我只會這樣做,如果他們真的不變,像PI 。 對於可以更改的參數,我更喜歡使用具有實例級值的類。 我認為你需要這種靈活性來調整你的遺傳算法,或者一次使用多個參數集。 這是一種方法(不可變類):
public class GeneticAlgorithmParameters {
public double CrossoverRate { get; private set; }
...
public GenericAlgorithmParameters(double crossoverRate, ... others) {
CrossoverRate = crossoverRate;
...
}
}
現在,您將GeneticAlgorithmParameters
的實例GeneticAlgorithmParameters
給您的GeneticAlgorithm
類構造函數。
public static class Constants
{
public const string MyConstant = "constantValue";
}
你打電話給他們如下:
public void MyMethod
{
var string = Constants.MyConstant;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.