我正在尝试制作一个化学方程式的平衡器。为此,我创建了一个元素元素:
class Element
{
public elemEnum ElemType {get; set;}
public double Amount {get; set;} // How many atoms of this type in the formula
}
* elemEnum
是所有化学元素的枚举。
我想让set
为ElemType
解析一个字符串到枚举,但由于set
只能接受与value
相同类型的值,我决定添加方法:
public void SetElemType(string type)
{
this.ElemType = (elemEnum)Enum.Parse(typeof(elemEnum), type);
}
是否可以通过ElemType
方法设置SetElemType
属性,而无需使用private
并添加GetElemType
方法?< / p>
答案 0 :(得分:1)
由于评论中最明显的解决方案尚未写成答案:
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;
}
}
此解决方案可能会使用您的类混淆开发人员,因为设置该属性将不起作用。如其他人所说,使用私有设置器来完成任务会更好 。我只是想展示另一种方法。