繁体   English   中英

类可以返回自身的静态实例吗? (在C#中)

[英]Can a class return a static instance of itself? (in c#)

现在,我的课程设置为:

enum Unit{Inches,Centimeters};

稍后,我执行一个步骤,将每个单元的所有属性设置为类实例变量。 例如:

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;
}

我宁愿将其全部存储在Unit类或struct中。 然后,我希望能够以与访问颜色相同的方式访问它。 您说Color.Blue代表蓝色,我想说Unit.Inches代表英寸...这就是为什么我不制作单位基类并只是扩展它。

我知道有办法做到这一点! 谁能启发我?

谢谢!

您可以使用静态属性:

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.

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