C#中使用反射以及特性简化的实例代码


本文摘自PHP中文网,作者黄舟,侵删。

假设现在有一个学生类(Student)


1

2

3

4

5

6

7

8

9

{  { name =

 

Age { ; 

 

Address { ;

如果需要判断某些字段(属性)是否为空,是否大于0,便有以下代码:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

public static string ValidateStudent(Student student)

        {

            StringBuilder validateMessage = new StringBuilder();           

            if (string.IsNullOrEmpty(student.Name))

            {

                validateMessage.Append("名字不能为空");

            }            if (string.IsNullOrEmpty(student.Sex))

            {

                validateMessage.Append("性别不能为空");

            }            if (student.Age <= 0)

            {

                validateMessage.Append("年龄必填大于0");

            }           

            //...... 几百行           

            // 写到这里发现不对啊,如果必填项有20多个,难道我要一直这样写吗!

            return validateMessage.ToString();

        }

这样的代码,重用性不高,而且效率低。

我们可以用特性,反射,然后遍历属性并检查特性。

首先自定义一个【必填】特性类,继承自Attribute


1

2

3

4

5

6

7

8

9

10

11

12

/// <summary>

/// 【必填】特性,继承自Attribute    /// </summary>

public sealed class RequireAttribute : Attribute

{        private bool isRequire;        public bool IsRequire

    {            get { return isRequire; }

    }        /// <summary>

    /// 构造函数        /// </summary>

    /// <param name="isRequire"></param>

    public RequireAttribute(bool isRequire)

    {            this.isRequire = isRequire;

    }

}

然后用这个自定义的特性标记学生类的成员属性:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

/// <summary>

    /// 学生类    /// </summary>

    public class Student

    {  

        /// <summary>

        /// 名字        /// </summary>

        private string name;

        [Require(true)]        public string Name

        {            get { return name; }            set { name = value; }

        }        /// <summary>

        /// 年龄        /// </summary>

        [Require(true)]        public int Age { get; set; }        /// <summary>

        /// 地址        /// </summary>

        [Require(false)]        public string Address { get; set; }        /// <summary>

        /// 性别        /// </summary>

        [Require(true)]

        public string Sex;

    }

通过特性检查类的属性:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

/// <summary>

      /// 检查方法,支持泛型        /// </summary>

      /// <typeparam name="T"></typeparam>

      /// <param name="instance"></param>

      /// <returns></returns>

      public static string CheckRequire<T>(T instance)

      {           

      var validateMsg = new StringBuilder();           

      //获取T类的属性

          Type t = typeof (T);           

          var propertyInfos = t.GetProperties();           

          //遍历属性

          foreach (var propertyInfo in propertyInfos)

          {               

          //检查属性是否标记了特性

              RequireAttribute attribute = (RequireAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof (RequireAttribute));               

              //没标记,直接跳过

              if (attribute == null)

              {                   

              continue;

              }               

              //获取属性的数据类型

              var type = propertyInfo.PropertyType.ToString().ToLower();               

              //获取该属性的值

              var value = propertyInfo.GetValue(instance);               

              if (type.Contains("system.string"))

              {                   

              if (string.IsNullOrEmpty((string) value) && attribute.IsRequire)

                      validateMsg.Append(propertyInfo.Name).Append("不能为空").Append(",");

              }               

              else if (type.Contains("system.int"))

              {                   

              if ((int) value == 0 && attribute.IsRequire)

                      validateMsg.Append(propertyInfo.Name).Append("必须大于0").Append(",");

              }

          }            return validateMsg.ToString();

      }

执行验证:


1

2

3

4

5

6

7

8

static void Main(string[] args)

        {            var obj = new Student()

            {

                Name = ""

            };

            Console.WriteLine(CheckRequire(obj));

            Console.Read();

        }

结果输出:

有人会发现,Sex也标记了[Require(true)],为什么没有验证信息,这是因为,Sex没有实现属性{ get; set; },GetProperties是获取不到的

以上就是C#中使用反射以及特性简化的实例代码的详细内容!

相关阅读 >>

c#根据表格偶数与奇数加载不同颜色的实例分析

c# .net 将list序列化

c#中实现复制与删除文件的方法

c#中关于async与await的使用详解

c#集合类有哪些?

c#中使用反射以及特性简化的实例代码

c#中在构造函数中访问虚成员有什么问题?

c#实现json序列化删除null值的方法实例

.net是什么语言 视频

linux下搭建.net core环境方法步骤

更多相关阅读请进入《csharp》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...