[英]OOP Class Design
I have this code, 我有这个代码,
public abstract class BaseClass
{
public object CommonMethod<T>()
{
//Common code
CustomMethod(); //Call child method
return (T)CustomObject;
}
internal abstract void CustomMethod();
}
public class ChildClass : BaseClass
{
public MyDTO CommonMethod()
{
return (MyDTO)base.CommonMethod<MyDTO>(); //Call Base class common code
}
internal override void CustomMethod()
{
//Custom Code, specific to child class
}
}
I have some common code which I have placed in the base class (BaseClass.CommonMethod), But finally same method should run child class specific code (ChildClass.CustomMethod). 我有一些常见的代码,我已经放在基类(BaseClass.CommonMethod),但最后同样的方法应该运行子类特定的代码(ChildClass.CustomMethod)。
Is this implementation correct or is there any other preferred/better implementation to achieve this? 这个实现是否正确或是否有任何其他首选/更好的实现来实现这一目标?
Final code (Updated according to the answers) : 最终代码(根据答案更新):
public abstract class BaseClass<T> where T : IDTO
{
public T CommonMethod()
{
//Common code
CustomMethod(); //Call child method
return (T)CustomObject;
}
internal abstract void CustomMethod();
}
public class ChildClass : BaseClass<MyDTO>
{
internal override void CustomMethod()
{
//Custom Code, specific to child class
}
}
I don't think you need the cast (MyDTO)base.CommonMethod<MyDTO>();
我认为你不需要演员(MyDTO)base.CommonMethod<MyDTO>();
as your base method is already casting the result. 因为您的基本方法已经在转换结果。
You will need to make sure that CustomObject
can be cast to T
, that bit looks fishy to me. 你需要确保将CustomObject
为T
,这个位看起来很可疑。
CustomerObject
must inherit from MyDTO
, therefore T
must implement MyDTO
( I think ) CustomerObject
必须从MyDTO
继承,因此T
必须实现MyDTO
( 我认为 )
With small corrections your code looks good. 通过小的修正,您的代码看起来很好。 You don't need to override CommonMethod, though, if you put return value as T: 但是,如果将返回值设为T,则不需要覆盖CommonMethod:
public abstract class BaseClass<T>
{
public T CommonMethod()
{
//Common code
T result = CustomMethod(); //Call child method
return result;
}
internal abstract T CustomMethod();
}
public class ChildClass : BaseClass<MyDTO>
{
internal override MyDTO CustomMethod()
{
//Custom Code, specific to child class
}
}
In my example I assumed that you return CustomObject from CustomMethod, otherwise I'm not quite sure where are you getting this object from. 在我的示例中,我假设您从CustomMethod返回CustomObject,否则我不太确定您从哪里获取此对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.