gpt4 book ai didi

C# 多态性

转载 作者:太空宇宙 更新时间:2023-11-03 16:20:49 26 4
gpt4 key购买 nike

我是多态性的新手并且有点挣扎。

我有三个类(class)。作为基类的 Visit 类。然后是送货和取货。

送货和取货都是访问。

我希望能够引用访问类并与送货和取货交谈。

    public virtual class Visit
{
private string customerName;
private string customerAddress;
private DateTime arrivalTime;

public string customername
{
//name properties
set { customerName = value; }
get { return customerName; }
}

public string customeraddress
{
//address properties
set { customerAddress = value; }
get { return customerAddress; }
}

public DateTime arrivaltime
{
//time proerties
set { arrivalTime = value; }
get { return arrivalTime; }
}
}

public class Delivery : Visit
/*
* Polymorphism, Delivery is also a visit.
*/
{
private string deliveryAddress;
private string deliveryName;

public string deliveryaddress
{
set { deliveryAddress = value; }
get { return deliveryAddress; }
}

public string deliveryname
{
set { deliveryName = value; }
get { return deliveryName; }
}

public string ToString()
{ //return Delivery details
return deliveryname + " " + deliveryaddress + " " + customername + " " + customeraddress + " " + arrivaltime;
}

}

public class Pickup : Visit
/*
* Polymorphism, pickup is also a visit.
*/
{
public string ToString()
{ //return Pickup details
return customername + " " + customeraddress + " " + arrivaltime.ToString();
}
}
}

最佳答案

首先你必须从基类中移除virtual

Visit v=new Pickup();
v.customeraddress = "some address";
v=new Delivery();
v.customeraddress = "some address";

正如您在上面的示例中看到的那样,v 是一种 Visit,但我允许它指向 Pickup< 的实例Delivery 对分配的实例类型具有不同的行为。

关于C# 多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13969772/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com