通过引用获取子类的值

时间:2014-09-23 21:02:49

标签: c# subclass pass-by-reference

考虑我为自己的教育编写的以下代码。我有一个main方法,一个静态方法和两个类 - hold和subhold。 Subhold延长了。

 class Program
{
    static void Main(string[] args)
    {
        hold h = new hold();
        h.aa = 88;
        Console.WriteLine("In main " + h.aa);
        thismethod(h);
        Console.WriteLine("In main2 " + h.aa);
        Console.WriteLine("In main3 " + h.ss);  //ERROR

        Console.ReadKey();
    }

   static void thismethod (hold h) {
       Console.WriteLine("In thismdethod " + h.aa);

       h.aa += 1;
       Console.WriteLine("In thismdethod1 " + h.aa);
       h = null;
       subhold subhold = new subhold();

       subhold.aa = 8888;
       subhold.ss = 22222;

       h = subhold;

    }


}

class hold
{
    public int aa { get; set; }

}

class subhold : hold
{
    public int ss { get; set; }
}

我正在尝试访问h.ss.现在我无法访问它。如何从主方法访问h.ss

2 个答案:

答案 0 :(得分:2)

基类不会(更重要的是不应该)了解派生类的任何内容  属性。不同的派生类可以具有不同的添加属性集。  让基类意识到这一点会抵消对象的重要原则  导向设计

    static void Main(string[] args)
    {
        subhold h = new subhold();
        h.aa = 88;
        Console.WriteLine("In main " + h.aa);
        thismethod(h);
        Console.WriteLine("In main2 " + h.aa);
        Console.WriteLine("In main3 " + h.ss);  //no ERROR

        Console.ReadKey();
    }

答案 1 :(得分:1)

如果您通过引用传递h,则thismethod会将主h更改为指向subhold的实例。

h中的变量Main仍然声明hold。因此,您需要将其投放到subhold才能访问ss

static void Main(string[] args)
{
    hold h = new hold();
    h.aa = 88;
    Console.WriteLine("In main " + h.aa);
    thismethod(ref h);
    Console.WriteLine("In main2 " + h.aa);
    Console.WriteLine("In main3 " + ((subhold)h).ss);   // casted, no error.

    Console.ReadKey();
}

static void thismethod (ref hold h) {                   // passing by reference
   Console.WriteLine("In thismdethod " + h.aa);

   h.aa += 1;
   Console.WriteLine("In thismdethod1 " + h.aa);
   h = null;
   subhold subhold = new subhold();

   subhold.aa = 8888;
   subhold.ss = 22222;

   h = subhold;
}