c# - 合并泛型

标签 c# .net generics

我在 C#.net 中开发,我相信我需要使用泛型来解决我遇到的问题,但我不知道从哪里开始。

以下是我需要执行的步骤:

  1. 从用户那里获取 ID——完成
  2. 使用 ID 查询数据库表 - 完成
  3. 后退一行 - 完成
  4. 创建一个依赖于ID的对象类型
  5. 根据类型填充对象

不同的约会需要从数据库中提取(填充)不同的信息。例如,一个约会可能只需要用户的名字/姓氏,而另一个可能需要名字/姓氏/出生日期。

我想让子类先执行,再调用父类方法。问题是 myAppointment 在通过 Switch 语句后仍然被视为 Appointment 对象而不是 DoctorAppointment/OtherAppointment。在声明 myAppointment 的地方我实际上不知道它将是什么类型的对象

这是我目前拥有的代码:

        tblAppointment getAppointment = (from getApp in dc.tblAppointments
                                         where getApp.appID == Id
                                         select getApp).SingleOrDefault();

// Needs to be set the something. I really want this be to set to a generic type as I don’t really know what type it will be until it has been through the switch statement
Appointment myAppointment = null; 

            switch (getAppointment.tblAppointment.appTypeID)
            {
                case 2:
                    {
// Changes myAppointment from Appointment to DoctorsAppointment
                        myAppointment = new DoctorsAppointment();

                    }
                    break;
                case 1:
                    {
                        myAppointment = new OtherAppointment();
                    }
                    break;
                default:

                    break;

            }

// I want this to set myAppointment to DoctorsAppointment.Populate(getAppointment)
            return myAppointment.Populate(getAppointment);

约会是父类。 DoctorsAppointment/OtherAppointment 是子类。

子类中的 Populate 需要参数,而父类不需要。我目前收到的错误是:

No overload for method 'Populate' takes '1' arguments

希望我已经解释清楚了。

谢谢,

克莱尔

最佳答案

一种解决方案是,在父类 Appointment 中,创建这样的方法:

public virtual void Populate( getAppointment) 
{
   // does nothing
}

然后在子类中:

public override void Populate( getAppointment) 
{
// do what you need
}

关于c# - 合并泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1232360/

相关文章:

c# - 您可以使用 SOAP 和 WSHttpBinding 对 WCF 服务进行 jQuery 调用吗?

c# - 直接从 Dictionary<> 获取 KeyValuePair<>

.net - 如何在 Visual Studio 2013 中安装或使用 Xamarin

java - 通用类型列表的 Getter(作为参数传递)

c# - C# 4.0 中动态的 RuntimeBinderException

c# - 如何使概率随着时间的推移而增加并获得可预测的结果

c# - 如何不断延迟方法的执行

c# - 是否有 "String.Format"可以接受命名输入参数而不是索引占位符?

c# - 具有类型约束或基类参数的通用方法

Java 泛型 - 从 T 到 T 的类型不匹配