vendredi 31 juillet 2020

Does anyone has a nice built in PropertyAccessor object that could easily be used?

I have something similar to his:

public class ClassA
{
  public ClassB PropAnyStart {get;set;}
  public ClassB PropAnyEnd {get;set;}
}

public class ClassB
{
  public string Name {get;set;}
}


public void ProcessSomething(Accessor<ClassB> accessor) 
{
  ...
  if (accessor.Name = "Eric")
  {
       accessor = new ClassB(){Name = "SomeoneElse"};
  }
  ...
}

Accessor class does not exists, that's what I'm looking for. I want to call twice ProcessSomething like this:

{
  ClassA a = new ClassA();
  ...
  ProcessSomething(a.PropAnyStart.Accessor());
  ProcessSomething(a.PropAnyEnd.Accessor());
}

What is the closest way to do that in C# in 2020?

Update

I'm actually using this class:

public class PropertyAccessor<T>
    {
        Func<T> _getter;
        Action<T> _setter;

        public PropertyAccessor(Func<T> getter, Action<T> setter)
        {
            _getter = getter;
            _setter = setter;
        }

        public T Get()
        {
            return _getter();
        }

        public void Set(T val)
        {
            _setter(val);
        }
    }

But I have to pass arguments like that and its very tedious and take a long time:

ProcessSomething(new PropertyAccessor<ClassB>(() => a.PropAnyStart, (bArg) => a.PropAnyStart = bArg));

It should exists a better way to achieve my goal?





Aucun commentaire:

Enregistrer un commentaire