C# 三个具有常用方法的类
我在数据访问项目中有3个类,所有3个类都有许多数据访问方法(C# 三个具有常用方法的类,c#,C#,我在数据访问项目中有3个类,所有3个类都有许多数据访问方法(GetSomeList,InsertSomeData,UpdateSomeData)。 所有3个类都有几个相同的方法。 我不想写同样的方法三次。 这里最好的方法是什么 一种可能的解决方案是定义一个将被继承的公共类。 这是好办法吗 例如: public abstract class CommonDataLayer { public int CommonMethod() { Random random = n
GetSomeList
,InsertSomeData
,UpdateSomeData
)。
所有3个类都有几个相同的方法。
我不想写同样的方法三次。
这里最好的方法是什么
一种可能的解决方案是定义一个将被继承的公共类。
这是好办法吗
例如:
public abstract class CommonDataLayer
{
public int CommonMethod()
{
Random random = new Random();
int randomNumber = random.Next(0, 100);
return randomNumber;
}
}
public class FirstDataLayer : CommonDataLayer
{
public int FirstMethod()
{
return CommonMethod() + 1;
}
}
public class SecondDataLayer : CommonDataLayer
{
public int SecondMethod()
{
return CommonMethod() + 2;
}
}
public class ThirtDataLayer : CommonDataLayer
{
public int ThirtMethod()
{
return CommonMethod() +3;
}
}
为所有类和超类的通用方法实现创建一个超类。一个好方法是: 一种可能的解决方案是定义一个将被继承的公共类。这是好办法吗 对 但是在您的代码示例中,没有必要使用
FirstMethod
、SecondMethod
和ThirdMethod
。
您可以直接从派生类调用CommonMethod
。如果派生方法需要特定功能,则可以重写CommonMethod
public class FirstDataLayer : CommonDataLayer
{
// This class uses CommonMethod from the Base Class
}
public class SecondDataLayer : CommonDataLayer
{
@Override
public int CommonMethod(){
// EDIT code
// Class specific implementation
return base.CommonMethod() +1;
}
}
public class ThirdDataLayer : CommonDataLayer
{
public int ThirdMethod(){
// Class specific implementation
return base.CommonMethod() +2;
}
}
可能重复感谢您的帮助。我修正了我的例子,以便更清楚我想要什么。