C# 多态性

标签 c# oop polymorphism

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

我有三个类(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/

相关文章:

c++ - 理解 C++ 中的多态性

c# - 无法将类型为 'MongoDB.Bson.Serialization.Serializers.DateTimeSerializer' 的对象转换为类型 'MongoDB.Bson.Serialization.IBsonSerializer`

c# - 如何在 Xamarin Forms 中从父级调用子 xaml 中的方法?

c++ - 具有某些成员的类的术语

c++ - 为什么不能不创建实例就不能使用多态类

java - Java如何选择多态中的重载方法

c# - while (k >= 0 && arr[k] > 0) 安全吗?

c# - 带有数组参数的过滤器定义 (SQL : WHERE IN)

javascript - jQuery AJAX 问题?或者 JS OOP 范围问题?

c# - 使用反射通过对象递归并打印树