学习 SQL Server CLR 没有多久,就遇到了一个让我很郁闷的问题;如何处理当“用户定义类型”中因出现像 string 这样的引用类型而引发地一些问题?

下面是我经过查询相关资料而得出的解决方法(代码所示):

  1 using System;
  2 using System.Data;
  3 using System.Data.SqlClient;
  4 using System.Data.SqlTypes;
  5 using Microsoft.SqlServer.Server;
  6 
  7 [Serializable]
  8 [Microsoft.SqlServer.Server.SqlUserDefinedType(Format.UserDefined, MaxByteSize=10)]
  9 public struct AgeGroup : INullable, IBinarySerialize
 10 {
 11     public override string ToString()
 12     {
 13         return ageGroup;
 14     }
 15 
 16     #region 自动生成
 17 
 18     public bool IsNull
 19     {
 20         get
 21         {
 22             return m_Null;
 23         }
 24     }
 25 
 26     public static AgeGroup Null
 27     {
 28         get
 29         {
 30             AgeGroup h = new AgeGroup();
 31             h.m_Null = true;
 32             return h;
 33         }
 34     }
 35 
 36     #endregion
 37 
 38     public static AgeGroup Parse(SqlString s)
 39     {
 40         if (s.IsNull)
 41             return Null;
 42         AgeGroup u = new AgeGroup();
 43         u.ageGroup = AgeGroup.ComputeAgeGroup(s.Value);
 44         return u;
 45     }
 46 
 47     /// <summary>
 48     /// 计算年龄段
 49     /// </summary>
 50     /// <param name="s">用户输入字串</param>
 51     /// <returns></returns>
 52     public static string ComputeAgeGroup(string s)
 53     {
 54         int tempInt = -1;
 55 
 56         if (int.TryParse(s, out tempInt))
 57         {
 58             if (tempInt >= 0)
 59             {
 60                 if (tempInt <= 6)
 61                 {
 62                     return "童年";
 63                 }
 64                 else if (tempInt > 6 && tempInt <= 17)
 65                 {
 66                     return "少年";
 67                 }
 68                 else if (tempInt > 17 && tempInt <= 40)
 69                 {
 70                     return "青年";
 71                 }
 72                 else if (tempInt > 40 && tempInt <= 65)
 73                 {
 74                     return "中年";
 75                 }
 76                 else
 77                 {
 78                     return "老年";
 79                 }
 80             }
 81             else
 82             {
 83                 return string.Empty;
 84             }
 85         }
 86         else
 87         {
 88             return string.Empty;
 89         }
 90     }
 91 
 92     // 年龄段名称
 93     public string ageGroup;
 94     // 标示是否为空(自动生成)
 95     private bool m_Null;
 96 
 97     #region IBinarySerialize 成员
 98 
 99     public void Read(System.IO.BinaryReader r)
100     {
101         this.ageGroup = r.ReadString();
102     }
103 
104     public void Write(System.IO.BinaryWriter w)
105     {
106         w.Write(this.ageGroup);
107     }
108 
109     #endregion
110 }
111 
112 
113 

相关文章: