简体   繁体   English

在c#中将默认值设置为成员类

[英]Set default value to member class in c#

I need to set a default value to a member class, this value can vary and it's set at the beginning of the execution; 我需要为成员类设置一个默认值,这个值可以变化,并在执行开始时设置; I have this so far, minScore is my default value 到目前为止我有这个,minScore是我的默认值

public class Zones : GeneralIndicator
{
   public int IndicatorType { get; set; } 
   public string Code { get; set; }
   public string Score { get; set; } //TODO: calcular desde aca el score usando el indicatortype
   public double Latitude { get; set; }
   public double Longitude { get; set; }

   private int minScore = 0;

   public void setMinScore(int value)
   {
      minScore = value;
   }
}

I get the minScore value as a parameter when calling the application. 我在调用应用程序时将minScore值作为参数。 What's the best way to set minScore for every object generated in runtime? 为运行时生成的每个对象设置minScore的最佳方法是什么?

Two options: 两种选择:

  • Create a ZonesFactory class, which takes a defaultMinScore in the constructor (to remember) and has a CreateZones method which creates an instance and sets the min score: 创建一个ZonesFactory类,它在构造函数中记住defaultMinScore (要记住),并有一个CreateZones方法,它创建一个实例并设置最小分数:

     public class ZonesFactory { private readonly int defaultMinScore; public ZonesFactory(int defaultMinScore) { this.defaultMinScore = defaultMinScore; } public Zones CreateZones() { return new Zones(defaultMinScore); } } 

    Note that here I'm assuming you also create a new constructor for Zones which takes the minScore as a parameter. 请注意,这里我假设您还为Zones创建了一个新的构造函数,它将minScore作为参数。 I suggest you get rid of the setMinScore method (which violates .NET naming conventions apart from anything else). 我建议你摆脱setMinScore方法(除了其他任何东西,它违反了.NET命名约定)。

  • Use a static variable to keep the default, and set it in the Zones constructor 使用静态变量保持默认值,并在Zones构造函数中设置它

Personally I'd prefer the first of these. 就个人而言,我更喜欢第一种。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM