如何实现Entity子类多态调用?规避强类型转换方案咨询
解决方案:利用多态实现子类专属行为(无需强转)
核心思路是通过多态让每个子类自行实现获取存储命名空间的逻辑,基类定义统一的抽象方法,调用时直接通过基类对象调用,自动触发子类的专属实现,完全不需要强类型转换。
步骤1:重构基类Entity,定义抽象方法
将原有的getStorePlace替换为抽象方法,强制子类实现自己的存储命名空间逻辑:
public abstract class Entity : IEntity { public string Id { get; set; } // 抽象方法:子类必须实现获取存储命名空间的逻辑 public abstract string GetStoreNamespace(); }
步骤2:子类WeatherEntity重写抽象方法
在子类中实现专属的命名空间判断逻辑:
public class WeatherEntity : Entity, IweatherEntity { public string name { get; set; } = null!; public int temperature { get; set; } public string location { get; set; } = null!; public bool isRainyToday { get; set; } = false; // 重写基类方法,实现WeatherEntity专属的存储命名空间规则 public override string GetStoreNamespace() { return temperature > 25 ? "ConsoleAppTest.Repositories.MongoRepositories" : "ConsoleAppTest.Repositories.JsonRepositories"; } }
步骤3:修改choose函数,移除强转
直接调用基类对象的抽象方法,利用多态自动调用子类实现:
public IRepository<Entity> Choose(Entity entity) { return _repositories.FirstOrDefault(h => h.GetType().Namespace == entity.GetStoreNamespace()); }
为什么这能解决问题?
- 多态特性确保:当你传入
WeatherEntity对象时,entity.GetStoreNamespace()会自动执行WeatherEntity中的重写逻辑,无需任何强转。 - 扩展性强:后续新增
Entity子类时,只需重写GetStoreNamespace方法,无需修改Choose函数,符合开闭原则。 - 类型安全:避免了强转可能引发的
InvalidCastException,代码更健壮。
内容的提问来源于stack exchange,提问作者Chamyyys
相关产品推荐
相关产品推荐

