gpt4 book ai didi

c# - 如何在方法中返回动态返回类型? C#

转载 作者:太空狗 更新时间:2023-10-29 22:07:45 25 4
gpt4 key购买 nike

我对方法的返回类型有疑问。

该方法返回一个 linq 对象,该对象目前返回类型 tblAppointment。该方法如下所示:

public tblAppointment GetAppointment(int id)
{
var singleAppointment = (from a in dc.tblAppointments
where a.appID == id
select a).SingleOrDefault();
return singleAppointment;

}

问题在于 tblAppointment 是抽象的并且有许多继承它的子类型。当我尝试返回类型为“appointmentTypeA”的对象并对其调用 .GetType() 方法时,它为我提供了正确的子类型,但是当我尝试访问属性时,它只允许我访问父属性.如果我获取该对象并将其转换为该子类型的新对象,那么它就可以工作并允许我访问我需要的所有内容,但它看起来很乱。

var viewSingleAppointment = appointmentRepos.GetAppointment(appointmentId);

Debug.Write(viewSingleAppointment.GetType()); //returns type i want

if (viewSingleAppointment is tblSingleBirthAppointment)
{
tblSingleBirthAppointment myApp = (tblSingleBirthAppointment)viewSingleAppointment; //need to do this to access TypeA properties for some reason

}

编辑:我已经完成了这项工作,但我需要为每个约会(大约 20 个)使用一个 select 语句,并将它们转换为适当的类型并检索属性,我不确定如何重构它,因为它将用于我们正在做的几页。

最佳答案

您正在解决错误的问题。如果您有一个父类(super class) A,其子类 BC 等都具有相似的功能,您需要执行以下操作:

  1. 使A成为BC等实现的接口(interface)。使用 BC 实例的代码通过 A 提供的接口(interface)来完成。如果您可以定义一组适用于所有类型的通用操作,那么这就是您需要做的全部。

  2. 如果您无法定义一组通用操作,例如您的代码类似于:

    A foo = GetA();
    if(foo is B) {
    B bFoo = (B) foo;
    // Do something with foo as a B
    } else if(foo is C) {
    C cFoo = (C) foo;
    // Do something with foo as a C
    } ...

    甚至这个(这基本上是同一件事,只是使用额外的信息来模拟类型系统已经为您提供的内容):

    A foo = GetA();
    MyEnum enumeratedValue = foo.GetEnumeratedValue();
    switch(enumeratedValue) {
    case MyEnum.B:
    B bFoo = (B) foo;
    // Do something with foo as a B
    break;
    case MyEnum.C:
    C cFoo = (C) foo;
    // Do something with foo as a C
    break;
    }

    那么你真正想要的是做类似的事情:

    A foo = GetA();
    foo.DoSomething();

    每个子类将实现 switch 语句的相应分支。这实际上在几个方面更好:

    • 它使用的整体代码更少。
    • 由于案例的实现存在于各种实现类中,因此不需要转换;他们可以直接访问所有成员变量。
    • 因为你不是在构建一个大的switch/case block separate从实际的BC 实现,如果添加新的子类,您不会有意外忘记添加相应的 case 的风险。如果您将 DoSomething() 方法留在 A 的子类之外,您将遇到编译时错误。

编辑:回应您的评论:

如果您的 DoSomething() 例程需要对 Form 或其他 GUI 元素进行操作,只需将该元素传递到方法中即可。例如:

public class B : A {
public void DoSomething(MyForm form) {
form.MyLabel.Text = "I'm a B object!";
}
}

public class C : A {
public void DoSomething(MyForm form) {
form.MyLabel.Text = "I'm a C object!";
}
}

// elsewhere, in a method of MyForm:

A foo = GetA();
foo.DoSomething(this);

或者,一个更好的主意可能是将您的 BC 类变成自定义控件,因为它们似乎封装了显示逻辑。

关于c# - 如何在方法中返回动态返回类型? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1455265/

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