业务需要 在类里附加一些属性。为了实现松耦合 。故在每个类里设置Attribute。
做了1天半 简单搞了个demo
代码
1 /// <summary>
2 /// 记录日志扩展属性
3 /// </summary>
4 [AttributeUsage(AttributeTargets.All,AllowMultiple=false,Inherited=false)]
5 public class LogHelpAttribute : Attribute
6 {
7 protected string _iAction;
8 protected bool _IsUse;
9 /// <summary>
10 ///
11 /// </summary>
12 public string iAction
13 {
14 get { return _iAction; }
15 set { _iAction = value; }
16 }
17
18 /// <summary>
19 /// 是否使用
20 /// </summary>
21 public bool IsUse
22 {
23 get { return _IsUse; }
24 set { _IsUse = value; }
25 }
26
27
28 }
29 public class LogHelp
30 {
31
32
33
34 }
上面是设置附加属性的CS
应用为:
代码
1 [LogHelp(iAction="News",IsUse=true)]
2 public partial class News
3 {
4 ///<summary>
5 ///添加数据
6 ///</summary>
7 ///<param name="m_News">实体类:NewsInfo</param>
8 ///<returns>返回插入行的主键ID,插入失败返回-1或者Guid.Empty</returns>
9 public static int Add(NewsInfo m_News){
10 string s_strsql="insert into t_News(nTitle,nType,nContent,nUserID,createtime,Hits) values(@nTitle,@nType,@nContent,@nUserID,@createtime,@Hits);select scope_identity();";
11 SqlParameter[] paramslist={
12 new SqlParameter("@nTitle",m_News.NTitle),
13 new SqlParameter("@nType",m_News.NType),
14 new SqlParameter("@nContent",m_News.NContent),
15 new SqlParameter("@nUserID",m_News.NUserID),
16 new SqlParameter("@createtime",m_News.Createtime),
17 new SqlParameter("@Hits",m_News.Hits)
18 };
19 object o=SqlHelper.ExecuteScalar(ConfigHelper.Connstring, CommandType.Text, s_strsql,paramslist);
20 if(o!=null && o!=DBNull.Value){
21 Type type=typeof(News);
22 LogHelpAttribute loghelp;
23 foreach(Attribute attr in type.GetCustomAttributes(true))
24 {
25 loghelp = attr as LogHelpAttribute;
26 if (loghelp != null)
27 {
28 if (loghelp.IsUse)
29 {
30 int result = ITGoods.UI.PageLogHelp.Add( "添加数据",loghelp.iAction);
31 }
32 }
33 }
34
35 return Convert.ToInt32(o);
36 }
37 return -1;
38 }
39 }