Class inheritance: recreate base class items (or instance) from a property of the inherited class

陌路散爱 提交于 2019-12-01 17:56:48

A tuple is immutable, so you can't change its values. When you have immutable objects, the way to change them is to return a new object with the desired properties changed. So if you want to stick with tuples, you could do something like this:

public static class TupleExtensions {
  public static Tuple<T1, T2, T3> 
    WhereItem3Is<T1, T2, T3>(this Tuple<T1, T2, T3> self, T3 newValue) {
    return Tuple.Create(self.Item1, self.Item2, newValue);
  }
  // other methods for Tuple<,,> or other Tuples...
}

And use it like this:

var t = Tuple.Create(1, 2, 3);
// ...
t = t.WhereItem3Is(4);

But it's a little bit painful to write all those methods. So if you need many of them, better just do this:

var t = Tuple.Create(1, 2, 3);
t = Tuple.Create(t1.Item1, t1.Item2, 4);

You could even have a wrapper type that you'd use to reference the tuple from different places in your code, so that any "changes" could be visible:

var t = Tuple.Create(1, 2, 3);
var r = new Ref<Tuple<int, int, int>>(t);
// share r ...
r.Value = Tuple.Create(r.Value.Item1, r.Value.Item2, 4);

...

public class Ref<T> {
  public T Value { get; set; }
  public Ref(T value) { Value = value; } 
}

All this, though, feels very awkward. Maybe you could better explain the essential problem you're having so that better answers could be provided. Maybe you don't really need a tuple after all, just something more specific to your domain.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!