[英]Can a class return a static instance of itself? (in c#)
Right now my class is set up as: 现在,我的课程设置为:
enum Unit{Inches,Centimeters};
Later on I have a step that sets all of the properties of each of these units into my classes instance variables. 稍后,我执行一个步骤,将每个单元的所有属性设置为类实例变量。 For example:
例如:
int unitBase; //10 for metric, 16 for american
int label;
switch(unit)
{
case Unit.Inches: unitBase = 16; unitLabel = "\"";break;
case Unit.Centimeters: unitBase = 10; unitLabel = "cm";break;
}
I would rather store this all in a Unit class or struct. 我宁愿将其全部存储在Unit类或struct中。 Then, I would like to be able to access it in the same way you access colors, for example.
然后,我希望能够以与访问颜色相同的方式访问它。 You say
Color.Blue
for a blue color, I would like to say Unit.Inches
for inches... That is why I dont make a unit base class and simply extend it. 您说
Color.Blue
代表蓝色,我想说Unit.Inches
代表英寸...这就是为什么我不制作单位基类并只是扩展它。
I know that there is a way to do this! 我知道有办法做到这一点! Could anyone enlighten me?
谁能启发我?
Thanks! 谢谢!
You can use static properties: 您可以使用静态属性:
public enum UnitSpecifier{Inches,Centimeters};
public class Unit
{
int unitBase; //10 for metric, 16 for american
string unitLabel;
public Unit(UnitSpecifier unit)
{
switch (unit)
{
case UnitSpecifier.Inches: unitBase = 16; unitLabel = @"\"; break;
case UnitSpecifier.Centimeters: unitBase = 10; unitLabel = "cm"; break;
}
}
public static readonly Unit Inches = new Unit(UnitSpecifier.Inches);
}
public struct Unit {
public static readonly Unit Inches = new Unit(16, "\"");
public static readonly Unit Centimeters = new Unit(10, "cm");
private readonly int _unitBase;
private readonly string _unitLabel;
static Unit() { }
private Unit(int unitBase, string unitLabel) {
this._unitBase = unitBase;
this._unitLabel = unitLabel;
}
public int UnitBase {
get { return this._unitBase; }
}
public string UnitLabel {
get { return this._unitLabel; }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.