标签:blog class code tar string get color int ble tab re
1、定义一个基类接口
|
1
2
3
4
5
6
7
8
9
10 |
public
interface IBaseEntity{/// <summary> 最后操作人编码 </summary>string
LastOperatorCode { get; set; }/// <summary> 最后操作人 </summary>string
LastOperator { get; set; }/// <summary> 最后操作时间 </summary>DateTime ModifyTime { get; set; }} |
2、然后有实体类实现相关字段
public
class MyEntity : IBaseEntity { /// <summary> 最后操作人编码 </summary> public
string LastOperatorCode { get; set; } /// <summary> 最后操作人 </summary> public
string LastOperator { get; set; } /// <summary> 最后操作时间 </summary> public
DateTime ModifyTime { get; set; }} |
3、在业务层写一个抽象类
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 |
public
abstract class SingleTableServices<T> : BaseServiceBase where
T : class,IBaseEntity, new(){public
T Add(T entity){entity = OnAdd(entity);entity.LastOperatorCode = GetUserId();entity.LastOperator = GetUserName();entity.ModifyTime = DateTime.Now;entity.OperateType = 1;//写数据库操作,未实现,注释后才可用if (!BaseDataRepository.Add(entity)){throw
new Exception("数据库底层执行新增失败!");}return
entity;}public
abstract T OnAdd(T entity);} |
|
1 |
注:where
T : class,IBaseEntity, new()是指泛型T的类型限制为类、IBaseEntity、和实例化的类型 |
4在实际操作的业务层继承引用这个抽象类的并重写OnAdd方法。
|
1
2
3
4
5
6
7
8
9 |
public
class MyService : SingleTableServices<WIColorEntity> { public
override WIColorEntity OnAdd(WIColorEntity entity) { //对实的其它字段的赋值操作,如果没有就直接返回 return
entity; } } |
5在实际操作的业务层的上一层。或UI可以直接调用Add(因为之前已经继承了抽象类,子类都拥有了他的方法)就可以实现业务的重用。
在实际执行时。
|
1 |
MyService 的Add方法执行。抽象类的Add方法内容,当执行到抽象类的抽象方法OnAdd时,系统又回来MyService 找到之前重写的OnAdd执行里面的内容。<br><br>NM感觉这么简单,不做笔记还真的用不好这个方法,至少前天的时候还是用不好。 |
|
1 |
<em id="__mceDel"><br>写给自己看的。不喜匆喷,谢谢。</em> |
用基类接品,泛型抽象类,抽象方法实现代码复用,码迷,mamicode.com
标签:blog class code tar string get color int ble tab re
原文地址:http://www.cnblogs.com/seanlau/p/3701847.html