使属性只能通过特定方法设置

时间:2015-10-18 09:58:04

标签: c# properties enums

我正在尝试制作一个化学方程式的平衡器。为此,我创建了一个元素元素:

class Element
{
    public elemEnum ElemType {get; set;}
    public double Amount {get; set;} // How many atoms of this type in the formula
}

* elemEnum是所有化学元素的枚举。

我想让setElemType解析一个字符串到枚举,但由于set只能接受与value相同类型的值,我决定添加方法:

public void SetElemType(string type)
{
    this.ElemType = (elemEnum)Enum.Parse(typeof(elemEnum), type);
}

是否可以通过ElemType方法设置SetElemType属性,而无需使用private并添加GetElemType方法?< / p>

3 个答案:

答案 0 :(得分:1)

由于评论中最明显的解决方案尚未写成答案:

使用private setter

class Element
{
    public ElemEnum ElemType {get; private set;}
    public double Amount {get; set;}

    public void SetElemType(string type)
    {
        this.ElemType = (ElemEnum)Enum.Parse(typeof(ElemEnum), type);
    }
}

这样,ElemType只能在您自己的班级中设置。

答案 1 :(得分:0)

正如已经指出的那样,您可以使用private setter,或者您可以将readonly属性与public getter一起使用,使用字段和方法来修改此字段:

class Element
{
   private elemEnum _elemType;

   public elemEnum ElemType { get { return _elemType; } }

   public void SetElemType(string type) 
   {
      this._elemType = (elemEnum)Enum.Parse(typeof(elemEnum), type);
   }

   public double Amount {get; } // How many atoms of this type in the formula
}

虽然它与private setter的属性几乎相同,但它使用的方法略有不同......

如果你真的只想让一个(!)方法改变值,你可以使用反射并添加包含枚举的类:

class MyElemSetter
{
    private readonly elemEnum elem;

    public MyElemSetter(elemEnum e, Action helperAction)
    {
        MethodInfo callingMethodInfo = helperAction.Method;

        if (helperAction.Method.Name.Contains("<SetElemType>")) elem = e;
    }

    public static implicit operator elemEnum(MyElemSetter e)
    {
        return e.elem;
    }
}

class Element
{
    private MyElemSetter _elemType;

    public elemEnum ElemType { get { return _elemType; } }

    public void SetElemType(string type)
    {
        this._elemType = new MyElemSetter((elemEnum)Enum.Parse(typeof(elemEnum), type), () => { });
    }

    public double Amount { get; set; } // How many atoms of this type in the formula
}

答案 2 :(得分:0)

  

无需将其设为私有

好吧,您可以通过向类中添加bool字段并稍微修改属性来创建变通方法解决方案。

class Element
{
    private bool _elemCanBeSet = false;
    private elemNum _elemType;

    public elemEnum ElemType
    {
        get { return _elemType; }
        set { if (_elemCanBeSet) _elemType = value; }
    }

    public double Amount {get; set;} // How many atoms of this type in the formula

    public void SetElemType(string type)
    {
        _elemCanBeSet = true;
        this.ElemType = (elemEnum)Enum.Parse(typeof(elemEnum), type);
        _elemCanBeSet = false;
    }
}

此解决方案可能会使用您的类混淆开发人员,因为设置该属性将不起作用。如其他人所说,使用私有设置器来完成任务会更好 。我只是想展示另一种方法。