类继承:重新从继承类的属性基类的物品(或实例) [英] Class inheritance: recreate base class items (or instance) from a property of the inherited class

查看:157
本文介绍了类继承:重新从继承类的属性基类的物品(或实例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • 我有一个从B.结果
    继承类A

    • A作为,我想从B到修改某些只读属性

    • 隐藏新的这些属性是不是一个合适的选择,导致基类有使用其自己的属性...

    • 某些功能 T选用override关键字,导致性能未标记为抽象的,虚拟的,也没有覆盖

    所以我想知道是否从继承类(b)我完全可以重新创建我的对象访问这些只读属性的实际实例。

    So I'd like to know whether from the inherited class (B) I can totally recreate the actual instance of my object to access those readonly properties.

    有关例如,为更加美好的解释,对于一个类继承元组,如果有可能后,我会做这样的事情:

    For example and for a better explaination, for a class inheriting Tuple, if it was possible, I would do something like this:

        public new T3 Item3
        {
            get { return item3; }
            set 
            {
                item3 = value;
                base = new Tuple<T1, T2, T3>(Item1, Item2, Item3); // Not valid
            }
        }
    



    我看不到如何做到这一点?

    I can't see how to do this?

    推荐答案

    一个元组是不可变的,所以你不能改变它的值。当你有不可变对象,改变他们的方式与所需的性质改为返回一个新的对象。所以,如果你想坚持的元组,你可以做这样的事情:

    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...
    }
    

    和使用这样的:

    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.

    这篇关于类继承:重新从继承类的属性基类的物品(或实例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆