c# - 多态性难题
问题描述
现在,我很欣赏这实际上是一个基于意见的问题,所以我希望它会被关闭,但希望不会在一些答案出现之前。我正在处理的主题对我来说是新的,但它也是巨大的。我可以在这里呆一年,但仍然只是冰山一角,这就是为什么我让自己有点卡住了。
所以,我有三个真实世界对象的情况,我们称它们为 HelloWorld、Foo 和 Bar。Bar 具有与 Foo 相同的所有属性,除了一个。此特定属性对 Bar 无效。相反,Bar 具有该类型独有的附加属性。所以,在我看来,Bar 继承 Foo 是有道理的。现在,一个 HelloWorld 可以有一个 Foo 或一个 Bar ,具体取决于环境,并且操作将根据它所持有的不同而进行。
我想知道的是——下面的例子是否有水,或者它是否有一种代码闻起来像阳光下一周大的黑线鳕?!如果它确实有气味,那么“正确”的方法是什么?这是全新的代码——我不是在重构,所以我有能力在第一时间把它做好。
public class Foo
{
// This property is valid for Foo AND Bar
public int Property1 { get; set;}
// This property is valid for Foo ONLY.
public virtual string Property2 { get; set;}
}
public class Bar
{
// This cannot exist in Bar - so always return null, don't allow it to be set.
public new string Property2 => null;
// Unique to Bar.
public List<int> Property3 { get; set;}
}
public class HelloWorld
{
public Foo FooProperty { get; private set;}
private HelloWorld()
{
}
// Create a new object with the property as a Foo.
public static HelloWorldWithFoo()
{
return new HelloWorld()
{
FooProperty = new Foo()
};
}
// Create a new object with the property as a Bar.
public static HelloWorldWithBar()
{
return new HelloWorld()
{
FooProperty = new Bar()
};
}
}
编辑
好的-所以我的“通用”示例可能缺少所需的上下文-抱歉。在接受了评论等之后,我已经像这样应用它 - 并且为了清晰起见使用了真实世界的类型。
public class Slot
{
public CardBase CardDetails { get; set; }
private Slot()
{
}
public static Slot CreateSlotWithCard()
{
return new Slot()
{
CardDetails = new Card()
};
}
public static Slot CreateSlotWithCarrierCard()
{
return new Slot()
{
CardDetails = new CarrierCard()
};
}
}
public class CardBase
{
public string Name { get; set; }
public DateTime InstallationDate { get; set; }
public HardwareType Type { get; set; }
}
public class Card : CardBase
{
public List<int> Ports { get; set; }
}
public class CarrierCard : CardBase
{
public List<Card> SubCards { get; set; }
}
这看起来更符合正确的路线吗?
解决方案
所以,在我看来,Bar 继承 Foo 是有道理的......
我认为这不应该是这样的。我认为您希望他们都从另一个公共类继承来保存他们共享的东西。让他们保留那些让他们与众不同的东西。
public class Common
{
// This property is valid for Foo AND Bar
public int Property1 { get; set; }
}
public class Foo : Common
{
// This property is valid for Foo ONLY.
public string Property2 { get; set; }
}
public class Bar : Common
{
// This cannot and *hence will not* exist in Bar.
// public new string Property2;
// This property is valid for Bar ONLY.
public List<int> Property3 { get; set; }
}
推荐阅读
- java - 我的 history() 方法面临的问题,我如何根据最旧的更改进行排序?
- schema.org - 如何为 Schema.org 'Preschool' 编写营业时间?
- elm - 在 Elm 中格式化字符串
- rest - Grails RESTful 映射到嵌套资源的预期默认行为
- python - 一次读取多个图像
- ios - Xcode 11 无法打开项目/崩溃
- c# - 从 json 下载图像不完整
- angular - 错误类型错误:无法读取空角度形式的属性“错误”,看不到嵌套的 FormBuilder 组
- javascript - 为了优化性能,我应该将 Web 数据存储为 CSV 还是 JSON?
- javascript - 如何防止导航栏重叠标题?