考虑我为自己的教育编写的以下代码。我有一个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
?
答案 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;
}