重构我的代码:在派生类中避免铸造 [英] Refactor my code : Avoiding casting in derived class
问题描述
首先,我觉得标题很抱歉,我不知道如何准确地描述我的问题。我希望这将是更好的通过代码解释
Firstly, I feel sorry about the title, I do not know how to describe my problem exactly. I hope it will be better explained through the code.
public abstract class AB {
public MyModel Model;
}
public class A : AB {
public A() {
Model = new MyModelA();
}
public void AMethod() {
var model = (MyModelA) model; // I have to do this all place
}
public void AnotherMethod() {
var model = (MyModelA) model; // same here
model.NewInt = 123;
}
}
public abstract class MyModel {
}
public class MyModelA : MyModel {
// new properties
public int NewInt {get;set;}
}
看看代码,以便使用从派生类新的属性,我必须做一个铸件,但它是丑陋的,当我不得不使用它同时全国各地的地方。
Take a look at the code, in order to use new properties from derived class, I have to do a cast but it is ugly when I have to use it same time all over places.
我想的方法是声明另一个属性:公共MyModelA _TMP
然后我投它在构造 _TMP =(MyModelA)型号
并使用它,而不是模型。
The method I think is declare another property: public MyModelA _tmp
then I cast it in the constructor _tmp = (MyModelA) Model
and use it instead of Model.
还有没有其他适当的方式做到这一点?
谢谢
Are there any other appropriate ways to do this ? Thanks !
推荐答案
您可以使基类通用的:
public abstract class ServiceBase<TModel> where TModel : new() {
protected ServiceBase() { Model = new TModel(); }
public TModel Model { get; private set; }
}
public class AService : ServiceBase<MyModelA> {
...
}
这篇关于重构我的代码:在派生类中避免铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!