gpt4 book ai didi

c# - 许多没有功能的派生类只能到 "know"它们的类型

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

我认为下面的问题有更好的解决方案。

假设我们有以下类结构:

class Foo
{
public int Id { get; set; }
}

class Bar1 : Foo
{

}

class Bar2 : Foo
{

}

class Bar3 : Foo
{

}
//.. A lot more of these Foo derivations

派生类没有任何功能。以下示例给出了这些类的用途:

  • 访问 Foo 对象列表中特定类型的特定对象(来自类型 Bar3 且 ID 为 5 的对象)。
  • 在 GUI 中显示与 Foo 类型的特定对象相关的不同数据。

有没有更好的方法来识别这些对象之一而不派生它们?

谢谢!

最佳答案

如果它们在语义上相同并且对衍生物没有意义,您可以创建一个Enum:

public enum SomeGreatEnum
{
Bar1,
Bar2,
Bar3
}

并为 Foo 添加一个属性:

class Foo
{
public SomeGreatEnum SomeGreatEnum { get; set; }
public int Id { get; set; }
}

现在您可以:

  1. 过滤器:

    foos.Where(x => x.SomeGreatEnum == SomeGreatEnum.Bar1);
  2. 根据枚举类型绑定(bind)到 GUI。

关于c# - 许多没有功能的派生类只能到 "know"它们的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28345132/

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