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

时间:2011-03-27 22:47:18

标签: 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类或结构中。然后,我希望能够以与访问颜色相同的方式访问它,例如。你说Color.Blue为蓝色,我想说Unit.Inches表示英寸......这就是为什么我不制作一个单位基类而只是扩展它。

我知道有办法做到这一点!谁能开导我?

谢谢!

2 个答案:

答案 0 :(得分:8)

您可以使用静态属性:

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

答案 1 :(得分:1)

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