现在,我意识到这实际上是一个基于观点的问题,所以我希望这个问题能够结束,但希望不会在一些答案出现之前。我所处理的主题对我来说是新的,但也是巨大的。我可以在这里呆一年,但仍然只是冰山一角,这就是我为什么会被困在这里的原因。
所以,我有三个真实世界的对象,让我们称它们为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; }
}这看上去更像正确的路线吗??
发布于 2019-02-28 10:49:22
正如你所指出的,这是一个基于意见的问题,所以我可以给你我自己对这个主题的看法,我认为大多数人都同意。
选择哪种类型继承其他类型应该来自概念模型,而不是它们的实现。因此,你不应该问Foo是否有这样的财产,而Bar是否有继承哪个?的属性,但您应该问Foo本质上是一种Bar还是反过来呢?如果两者都不是另一种类型,那么考虑为这两种类型编写抽象基类或接口。
发布于 2019-02-28 10:53:40
所以,在我看来巴尔继承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; }
}https://stackoverflow.com/questions/54923682
复制相似问题