C# 如何分配静态 class 的默认 属性 值
C# How to assign default property value of static class
如何在 C# 中分配静态 class 的默认 属性 值?我正在尝试执行以下操作:
public class Unit
{
public string Name;
public double cConvertFromSI;
}
// want to do something like this:
public static Unit m = (Name = "meter"; cConvertFromSI = 1;)
public static Unit mm = (Name = "millimeter"; cConvertFromSI = 1000;)
public static Unit in = (Name = "inch"; cConvertFromSI = 39.3701;)
首先,不要使用 public 字段,使用带有 getters/setters 的属性,它会破坏封装。其次,您应该实例化 Unit
的对象并初始化属性。查看一些示例:
public class Unit
{
public string Name { get; set; }
public double cConvertFromSI { get; set; }
}
public static Unit m = new Unit() { Name = "meter", cConvertFromSI = 1 };
public static Unit mm = new Unit() { Name = "millimeter", cConvertFromSI = 1000 };
public static Unit in = new Unit() { Name = "inch", cConvertFromSI = 39.3701 };
为什么不实现构造函数?为什么我们要创建一个 invalid Unit
实例(null
name
)?
public class Unit
{
public Unit(string name, double value)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(value));
Name = name;
cConvertFromSI = value;
}
// properties instead of fields
public string Name {get; private set; }
public double cConvertFromSI {get; private set; }
}
然后
public static Unit m = new Unit("meter", 1);
public static Unit mm = new Unit("millimeter", 1000);
public static Unit in = new Unit("inch", 39.3701);
如何在 C# 中分配静态 class 的默认 属性 值?我正在尝试执行以下操作:
public class Unit
{
public string Name;
public double cConvertFromSI;
}
// want to do something like this:
public static Unit m = (Name = "meter"; cConvertFromSI = 1;)
public static Unit mm = (Name = "millimeter"; cConvertFromSI = 1000;)
public static Unit in = (Name = "inch"; cConvertFromSI = 39.3701;)
首先,不要使用 public 字段,使用带有 getters/setters 的属性,它会破坏封装。其次,您应该实例化 Unit
的对象并初始化属性。查看一些示例:
public class Unit
{
public string Name { get; set; }
public double cConvertFromSI { get; set; }
}
public static Unit m = new Unit() { Name = "meter", cConvertFromSI = 1 };
public static Unit mm = new Unit() { Name = "millimeter", cConvertFromSI = 1000 };
public static Unit in = new Unit() { Name = "inch", cConvertFromSI = 39.3701 };
为什么不实现构造函数?为什么我们要创建一个 invalid Unit
实例(null
name
)?
public class Unit
{
public Unit(string name, double value)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(value));
Name = name;
cConvertFromSI = value;
}
// properties instead of fields
public string Name {get; private set; }
public double cConvertFromSI {get; private set; }
}
然后
public static Unit m = new Unit("meter", 1);
public static Unit mm = new Unit("millimeter", 1000);
public static Unit in = new Unit("inch", 39.3701);