实例访问继承抽象的类成员

时间:2017-02-23 16:55:50

标签: c#

这是星期四我猜的理论。

Main()不应该访问_XLocal& _YLocal?

using System;

namespace HelloGoodbyeOperator {

    public abstract class HGOperator {
        public string _greeting { get; set; }
        public bool _x { get; internal set; }
        public bool _y { get; internal set; }

        public static implicit operator HGOperator(bool mode) {
            object ret = new object();
            if (mode)
                ret = new HGOperator_Hello { _greeting = "hello", _XLocal = 10 };
            else
                ret = new HGOperator_Goodbye { _greeting = "goodbye", _YLocal = 20 };

            return (HGOperator)ret;
        }
    }



    public class HGOperator_Hello : HGOperator { 
        public int _XLocal { get; set; }
        public HGOperator_Hello() { _x = true; Console.WriteLine("HGOperator_Hello //" + _XLocal.ToString() + "\\\\"); }
    }



    public class HGOperator_Goodbye : HGOperator { 
        public int _YLocal { get; set; }
        public HGOperator_Goodbye() { _y = false; Console.WriteLine("HGOperator_Goodbye //", _YLocal, "\\\\"); }

    }



    class Program {
        static void Main(string[] args) {

            HGOperator hg = true;
            Console.WriteLine(hg._greeting);
            test(hg);

            Console.WriteLine("");

            hg = false;
            Console.WriteLine(hg._greeting);
            test(hg);

            Console.ReadKey();
        }

        static void test(HGOperator hg) {
            if (hg is HGOperator_Hello) {
                Console.WriteLine(hg._x);
                //Console.WriteLine(hg._XLocal);
            } else {
                Console.WriteLine(hg._y);
                //Console.WriteLine(hg._YLocal);
            }
        }
    }
}

这是输出

  

HGOperator_Hello // 0 \

     

您好

     

     

HGOperator_Goodbye //

     

再见

     

我可以理解如何尝试访问HGOperator_Hello类型的hg._YLocal将是一场噩梦&反之亦然。但我仍然认为我可以谨慎对待各自的成员。

另外,我打赌这是真的。这两个具体的构造函数没有_XLocal&的值。在Console.Writeline()上的_YLocal。没有.ToString()只打印一个“”。为什么不? 感谢。

1 个答案:

答案 0 :(得分:2)

问题是编译器不知道hgHGOperator_HelloHGOperator_Goodbye的派生类型。因此,在if内,您需要创建另一个变量并进行转换:

if (hg is HGOperator_Hello)
{
    var helloHg = (HGOperator_Hello)hg;
    Console.WriteLine(helloHg._x);
    Console.WriteLine(helloHg._XLocal);
}
else
{
    var goodbyeHg = (HGOperator_Goodbye)hg;
    Console.WriteLine(goodbyeHg._y);
    Console.WriteLine(goodbyeHg._YLocal);
}