Home Backend Development C#.Net Tutorial Simplified example code using reflection and features in C#

Simplified example code using reflection and features in C#

Sep 06, 2017 pm 01:48 PM
.net simplify

Suppose there is a student class (Student)


    
 
     
      
         
           {  { name = 
         
          Age { ;  
         
          Address { ;
Copy after login

If you need to determine whether some fields (attributes) are empty, Whether it is greater than 0, there will be the following code:


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();
        }
Copy after login

Such code has low reusability and low efficiency.

We can use attributes, reflection, and then iterate over the properties and check the attributes.

First customize a [required] attribute class, inherited from Attribute


    /// <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;
        }
    }
Copy after login

Then use this customized attribute to mark the member attributes of the student class:


/// <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;
    }
Copy after login

Check the properties of the class by attributes:


  /// <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();
        }
Copy after login

Perform validation:


static void Main(string[] args)
        {            var obj = new Student()
            {
                Name = ""
            };
            Console.WriteLine(CheckRequire(obj));
            Console.Read();
        }
Copy after login

Result output:

#Some people will find that Sex is also marked [Require(true)], why there is no verification information, this is because, Sex does not implement the properties {get; set; }, and GetProperties cannot be obtained

The above is the detailed content of Simplified example code using reflection and features in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the employment prospects of C#? What are the employment prospects of C#? Oct 19, 2023 am 11:02 AM

Whether you are a beginner or an experienced professional, mastering C# will pave the way for your career.

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

Convert numpy to list: an effective strategy to simplify data processing process Convert numpy to list: an effective strategy to simplify data processing process Jan 19, 2024 am 10:47 AM

NumPy is a very useful and widely used library in data processing and machine learning applications. An important feature of NumPy is that it provides a large number of tool functions for mathematical operations on arrays and matrices in Python, which makes NumPy an important tool in the field of scientific computing. However, in many cases we need to convert NumPy arrays to Python lists (or other similar data types) for better use in our code. Although NumPy arrays are in many ways better than P

.NET performance optimization technology for developers .NET performance optimization technology for developers Sep 12, 2023 am 10:43 AM

If you are a .NET developer, you must be aware of the importance of optimizing functionality and performance in delivering high-quality software. By making expert use of the provided resources and reducing website load times, you not only create a pleasant experience for your users but also reduce infrastructure costs.

Performance differences between Java framework and .NET framework Performance differences between Java framework and .NET framework Jun 03, 2024 am 09:19 AM

In terms of high-concurrency request processing, .NETASP.NETCoreWebAPI performs better than JavaSpringMVC. The reasons include: AOT early compilation, which reduces startup time; more refined memory management, where developers are responsible for allocating and releasing object memory.

PHP Arrow Functions: How to Simplify Loop Processing PHP Arrow Functions: How to Simplify Loop Processing Sep 13, 2023 am 08:15 AM

PHP Arrow Function: How to Simplify Loop Processing, Need Specific Code Examples Introduction: With the release of PHP7.4, arrow functions have become a very interesting new feature in PHP. The emergence of arrow functions makes us more concise and convenient when dealing with loops. This article will introduce the basic syntax of arrow functions and how to use arrow functions to simplify loop processing, and give specific code examples. The basic syntax of arrow functions The syntax of arrow functions is very simple and can be regarded as a shortcut way of writing anonymous functions. its grammatical structure

Null Coalesce operator in PHP7: How to simplify the conditional judgment of the code? Null Coalesce operator in PHP7: How to simplify the conditional judgment of the code? Oct 20, 2023 am 09:18 AM

NullCoalesce operator in PHP7: How to simplify the conditional judgment of the code? During the development process, we often need to perform conditional judgments on variables to determine whether they have a value or whether they are null. The traditional way is to use if statements or ternary operators to perform conditional judgments, but this way of writing seems lengthy and complicated in some cases. Fortunately, the NullCoalesce operator (??) was introduced in PHP7, which can help us simplify the way we write code and improve development efficiency. N

C# .NET Interview Questions & Answers: Level Up Your Expertise C# .NET Interview Questions & Answers: Level Up Your Expertise Apr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

See all articles