我试图让我的方法通用,我陷入困境,需要你的帮助.代码场景是我有一个抽象类说MyBaseAbs,其中包含常见属性:
public abstract class MyBaseAbs
{
public string CommonProp1 { get; set; }
public string CommonProp2 { get; set; }
public string CommonProp3 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在我有儿童班:
public class Mychild1: MyBaseAbs
{
public string Mychild1Prop1 { get; set; }
public string Mychild1Prop2 { get; set; }
public string Mychild1Prop3 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
和另一个孩子班:
public class Mychild2: MyBaseAbs
{
public string Mychild1Prop1 { get; set; }
public string Mychild2Prop2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在,我要创建一个需要的基础上执行某些操作的常用方法Mychild1和Mychild2,所以我所做的是:
public MyCustomClass SaveOperation<T>(T myObj)
where T : MyBaseAbs
{
SaveObject obj = new SaveObject();
}
Run Code Online (Sandbox Code Playgroud)
所以在这个方法里面我需要编写公共代码,SaveObject根据传递的子对象来做对象的映射.如何确定传递哪个对象并相应地使用属性.
一种选择是Save在基类中创建基本函数并使其成为虚函数.
然后覆盖子类中的方法.这种方式当你调用它的Save方法时SaveOperation,应该从正确的子类调用适当的方法.
public abstract class MyBaseAbs
{
public string CommonProp1 { get; set; }
public string CommonProp2 { get; set; }
public string CommonProp3 { get; set; }
public virtual void Save() { }
}
public class Mychild1: MyBaseAbs
{
public string Mychild1Prop1 { get; set; }
public string Mychild1Prop2 { get; set; }
public string Mychild1Prop3 { get; set; }
public override void Save() {
//Implementation for Mychild1
}
}
public class Mychild2: MyBaseAbs
{
public string Mychild1Prop1 { get; set; }
public string Mychild2Prop2 { get; set; }
public override void Save() {
//Implementation for Mychild2
}
}
Run Code Online (Sandbox Code Playgroud)