class TestA{
some code.....
}
class TestB{
.....
}
class Program{
void Main(){
TestA obj= new TestB();////When and why do we sometimes do this?
}
}
当我们不得不将一个对象引用到另一类时,有哪些不同的场景?
答案 0 :(得分:2)
我们没有。我们创建了一个名为obj
的变量,并将变量声明为TestA
类型。这意味着该变量可以包含对该IS-A TestA
的任何对象的引用。
然后创建一个TestB
对象。大概TestB
源自TestA
,这在您的问题中没有显示。但这意味着这个新对象通常是TestA
,尤其是TestB
。然后,我们将对此对象的引用分配给obj
变量。
哪个好。它仍然是TestB
对象。显然,只是这段代码并不打算使用任何B-ish
性质。只是它共享的核心A-ish
部分; TestB
类override
也可能是TestA
的某些成员,在这种情况下,当访问这些成员时,它仍将表现出B-ish
的性质。>
答案 1 :(得分:0)
从您的代码示例中,如果TestB从TestA继承,则可以使用此方法。如果不确定是什么继承,则应该阅读一些有关面向对象编程的知识。使用类创建其他对象的另一种方法是使用工厂模式。网络上也有很多有关此模式的信息。如果您使用的是工厂模式,则不会使用与代码中相同的构造方法(即,您不希望对象的新实例返回其他对象)。
答案 2 :(得分:0)
答案 3 :(得分:0)
我会告诉你如何:
多态性就像:
//an example of Polymorphism.
class FamilyMembers //parent class
{
public virtual void GetData() //it's virtual method cuz it can be overridden later
{
Console.WriteLine("Family");
}
}
class MyBrother : FamilyMembers //child class
{
public override void GetData() //the same method that we wrote before has been overridden
{
Console.WriteLine("Bro");
}
}
class Program
{
static void Main(string[] args)
{
//here's what u asking about
FamilyMembers myBrother = new MyBrother(); //MyBrother is a family member, the system now will choose the GetData() method from the child class MyBrother
myBrother.GetData();
Console.ReadLine();
}
}
界面就像:
public interface IFamily //the Parent Class
{
//an interface holds the signature of it's child properties and methods but don't set values
//Some properties signatures
int Age { get; set; }
string Name { get; set; }
//some methods
void PrintData();
}
public class MyBrother : IFamily //Child class that inherits from the parent class
{
//some properties, methods, fields
public string Name { get; set; } //public required
public int Age { get; set; } //public required
private string Collage { get; set; } //for my brother only
//constractor that sets the default values when u create the class
public MyBrother()
{
Name = "Cody";
Age = 20;
Collage = "Faculty of engineering";
}
////a method
void IFamily.PrintData()
{
Console.WriteLine("Your name is: " + Name + " and your age is: " + Age + " and you collage is: " + Collage);
}
}
class Program
{
static void Main(string[] args)
{
//now let's try to call the the methods and spawn the child classes :)
//spawn the child class (MyBrother) that inherits from the Family interface
//this is the answer of ur question
IFamily myBrother = new MyBrother(); // the constructor will auto-set the data for me so i don't need to set them
//printing the dude
myBrother.PrintData();
Console.ReadLine();
}
}
我希望这会做:)