c# - 当子类从父类继承时,有没有办法为继承的字段使用不同的数据类型来添加更多功能?
问题描述
当子类从父类继承时,有没有办法为继承的字段使用不同的数据类型来为不同子类中的字段添加更多功能?然后将这些子类用作一种可以用作函数参数的单一数据类型?
我需要创建两个具有一些相似性但又足够不同以保证拥有不同类的对象。所以我认为为他们设置一个基类是合适的。我在基类“ParentBase”中创建了两个道具,其中包含供子类使用的共享事物,子类需要为这些共享道具添加更多功能。
例如,ParentBase 中的 Settings 字段应该在 Parent1 和 Parent2 类中扩展以满足他们自己的独特需求。我觉得我需要创建新的数据类型来扩展 Parent1 和 Parent2 类的 Settings 字段。
class ParentBase
{
public ChildA Settings { get; set; }
public ChildX MoreSettings { get; set; }
// lots of shared props here that won't be extended in inheriting classes
public void SomeFunction()
{
// The inheriting class's Settings and MoreSettings props should be available to access here
// even though their data types are different to the base class's Settings and MoreSettings
// data types
}
}
class Parent1 : ParentBase
{
public ChildB Settings { get; set; }
public ChildY MoreSettings { get; set; }
}
class Parent2 : ParentBase
{
public ChildC Settings { get; set; }
public ChildZ MoreSettings { get; set; }
}
class ChildA { // base props and methods in here }
class ChildB : ChildA { // Parent1 specific functionality }
class ChildC : ChildA { // Parent2 specific functionality }
class ChildX { // base props and methods in here }
class ChildY : ChildX { // Parent1 specific functionality }
class ChildZ : ChildX { // Parent2 specific functionality }
我还需要在基类之外创建将 Parent1 或 Parent2 对象作为参数的函数。例如:
public void Calculate(SomeSharedType Parent1/Parent2 instance)
{
// need to access the Settings and MoreSettings properties here, and the base class's Setting should suffice,
// although it would be nice to access the inheriting class's Settings and MoreSettings properties
}
有没有办法让我通过继承或接口来实现这一点?
解决方案
这回答了你的问题了吗?
class ParentBase<T,U>
{
public virtual T Settings { get; set; }
public virtual U MoreSettings { get; set; }
}
class Parent1 : ParentBase<ChildB, ChildY>
{
public override ChildB Settings { get; set; }
public override ChildY MoreSettings { get; set; }
}
class Parent2 : ParentBase<ChildC, ChildZ>
{
public override ChildC Settings { get; set; }
public override ChildZ MoreSettings { get; set; }
}
尽管您应该注意,仅当您想更改属性行为时才需要覆盖,但为了仅更改类型,以下代码就足够了:
class ParentBase<T,U>
{
public T Settings { get; set; }
public U MoreSettings { get; set; }
}
class Parent1 : ParentBase<ChildB, ChildY>
{
}
class Parent2 : ParentBase<ChildC, ChildZ>
{
}
推荐阅读
- rust - 我怎样才能让一段运行代码超时?
- esp32 - ESP32 Analog Pin 4 Value 连接WIFI后刷新失败
- java - 带有滚动条的 JPanel 设置内容不可调整大小
- fullcalendar - rrule 获取每个月的第二个星期一、星期三和星期五
- python - 为什么字符串方法 str.format(value) 对于整数值和字符串值具有不同的空字符串默认填充?
- java - 如何在套件之前记录测试套件名称
- javascript - 如何在给定格式的 HTML 列表中显示 jQuery 数据值?
- sql - 使用 UNION ALL 和 RANK 优化 Hive 查询
- javascript - 如何获得不同颜色的字符串
- c# - 为 .NET Framework 接口实现接口隔离原则