Creating a property specified only by a specific method

I am trying to make a balancing equation of a chemistry equation. To do this, I created the Element class:

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

* elemEnumis the enum of all chemical elements.

I would like setto ElemTypeparse the string to be enumerated, but since it setcan only accept values ​​of the same type as value, I decided to add a method:

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

Is there an option for a property to ElemTypebe set only using a method SetElemTypewithout the need to create privateand add a method GetElemType?

+4
source share
3 answers

:

.

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

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

This solution may confuse the developer using your class, because setting the property will have no effect. Betteruse a private setter for their task, as others claim. I just wanted to show an alternative approach.

0
source

Source: https://habr.com/ru/post/1612116/


All Articles