请在下面说明代码 [英] Please Explain below mention Code
问题描述
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
1)Explain bold Line what does its mean.
MainClass obj = new DrivedClass();
obj.ID = 222;
obj.Name = "Changed";
obj.addNum(4, 3);
Console.WriteLine(obj.Name);
MainClass obj1 = new MainClass();
//DrivedClass obj2 = new MainClass();
Console.ReadKey();
}
}
public class MainClass
{
public Int32 ID;
public String Name;
public MainClass()
{
//do some things
}
public Int32 addNum(Int32 a,Int32 b)
{
return 3 * 5;
}
}
public class DrivedClass : MainClass
{
public DrivedClass()
{
ID = 123;
Name = "Qamar";
}
public void add()
{
}
}
}
解释为什么我们不在这种情况下访问驱动类方法。我们只访问方法,只在mainclass中定义为什么我们不访问驱动类方法。
为什么驱动的构造函数class首先调用然后是mainclass并再次驱动类。
Explain why we not access drive class method in this scenario.we access only method , that are defined in only mainclass why we not access drive class method.
Why the constructor of drive class is first calling then mainclass and again drive class.
推荐答案
MainClass obj = new DrivedClass();
MainClass obj = new DrivedClass();
在上面的行 obj
声明为 MainClass
类型。然后它被分配了一个 DrivedClass
实例。
这是合法的(确实编译器没有抱怨),但是,由于它的类型,你不能直接调用 obj
DrivedClass
方法。然而,你可以这样写:
In the above line obj
is declared of MainClass
type. Then it is assigned with a DrivedClass
instance.
That's legal (indeed the compiler doesn't complain), however, due to its very type, you cannot directly invoke on obj
the DrivedClass
methods. You may however write something like:
DrivedClass sameobj = obj as DrivedClass;
sameobj.Add();
这可以通过阅读本文完整解释 - C#中的继承,多态的介绍 [ ^ ]或C#上的任何其他入门书籍。
(PS下次正确标记您的问题)
This can be fully explained by reading this article - Introduction to inheritance, polymorphism in C#[^] or any other starter book on C#.
(P.S. Next time tag your question properly)
这篇关于请在下面说明代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!