当前位置:网站首页>Get properties of class
Get properties of class
2022-06-13 07:44:00 【freelooppowter】
use SQL When inserting or querying data in the form of script , Sometimes you need to list all the field names . And the way of using fixed code to write dead is undoubtedly not conducive to expansion . At this time, you can consider using reflection to obtain all the properties of the class , Then, the attribute names are spliced together to handle . Using return PropertyInfo Two of the arrays GetProperties Method , What needs to be noted is , Sometimes because of the framework or other reasons , You don't need to return all the attributes , It's time to take advantage of Linq Do some filtering .

Not much to say , Go straight to the code . Tool class and Class The class code is as follows :
using System;
using System.Linq;
using System.Reflection;
using System.Text;
namespace WindowsFormsApp1
{
public class RefelctHelper
{
public static string AllPublicFields<T>()
{
PropertyInfo[] propertyInfos = typeof(T).GetProperties();
StringBuilder stringBuilder = new StringBuilder();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
stringBuilder.Append(propertyInfo.Name + ",");
}
string fields = stringBuilder.ToString();
fields = fields.Substring(0, fields.LastIndexOf(','));
return fields;
}
public static string WithoutVirtualFields<T>()
{
PropertyInfo[] propertyInfos = typeof(T).GetProperties().Where(x => !x.GetMethod.IsVirtual).ToArray();
StringBuilder stringBuilder = new StringBuilder();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
stringBuilder.Append(propertyInfo.Name + ",");
}
string fields = stringBuilder.ToString();
fields = fields.Substring(0, fields.LastIndexOf(','));
return fields;
}
}
public class HasVirtualProperties : NormalClass
{
public virtual Guid Id { get; set; }
}
public class HasNoSetProperties : NormalClass
{
public string Comment
{
get { return $"Name:{Name}Address:{Address}"; }
}
}
public class NormalClass
{
public string Name { get; set; }
public string Nation { get; set; }
public string Address { get; set; }
}
}
Call location code :
Console.WriteLine($"Class {nameof(NormalClass)} Properties:{ RefelctHelper.AllPublicFields<NormalClass>()}");
Console.WriteLine($"Class {nameof(NormalClass)} Properties:{RefelctHelper.AllPublicFields<HasNoSetProperties>()}");
Console.WriteLine($"Class {nameof(NormalClass)} Properties:{RefelctHelper.AllPublicFields<HasVirtualProperties>()}");
Console.WriteLine($"Class {nameof(NormalClass)} Properties(excluded virtual properties):{RefelctHelper.WithoutVirtualFields<NormalClass>()}");
Console.WriteLine($"Class {nameof(NormalClass)} Properties(excluded virtual properties):{RefelctHelper.WithoutVirtualFields<HasNoSetProperties>()}");
Console.WriteLine($"Class {nameof(NormalClass)} Properties(excluded virtual properties):{RefelctHelper.WithoutVirtualFields<HasVirtualProperties>()}");The output is as follows :

take Name The access modifier is changed to protected、Nation The access modifier is changed to internal, Output is as follows :
It's not hard to see. GetProperties() Method returns all the public properties of the class , Including the inheritance from the parent class 、 No, Set Attribute 、 Virtual attribute, etc . If you want to get all the attributes, you can use the following method :
public static string AllFields<T>()
{
PropertyInfo[] propertyInfos = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
StringBuilder stringBuilder = new StringBuilder();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
stringBuilder.Append(propertyInfo.Name + ",");
}
string fields = stringBuilder.ToString();
fields = fields.Substring(0, fields.LastIndexOf(','));
return fields;
}You can use PropertyInfo Class MethodInfo Type of GetMethod Attribute to filter out the attributes that meet the needs .
| attribute | Access modifier |
|---|---|
| IsPublic | public |
| IsPrivate | private |
| IsFamily | protected |
| IsAssembly | internal |
| IsFamilyAndAssembly | C# I won't support it |
| IsFamilyOrAssembly | protected internal |

If the content helps you , You can scan the code to give me a reward , Your encouragement is my driving force .

边栏推荐
- 25 | adventure and prediction (IV): it's raining today. Will it rain tomorrow?
- Redis learning journey master-slave replication
- Redis learning journey - transaction
- Some optimization for seckill project
- 19 | establish data path (bottom): instruction + operation =cpu
- MySQL table partitioning
- 思路清晰的软光栅小引擎和四元数结合案例
- A learning dog
- Success logarithm of leetcode spells and potions
- 【clickhouse专栏】基础数据类型说明
猜你喜欢

A learning dog

How idea breaks point debugging

26 | Superscalar和VLIW:如何让CPU的吞吐率超过1

【深度学习】:《PyTorch入门到项目实战》(十二)卷积神经网络:填充(padding)和步幅(stride)

2022年G3锅炉水处理操作证考试题库模拟考试平台操作

Hashtable source code analysis

2021-10-08

A solution to the problem that there is always a newline character when C merges multiple RichTextBox contents

21 | pipeline oriented instruction design (Part 2): How did Pentium 4 fail?

Un des backtraders du cadre de quantification lit l'analyseur
随机推荐
Consistency under distributed
Find the first and last positions of elements in a sorted array
量化框架backtrader之一文讀懂Analyzer分析器
Data desensitization tool advance tool Datamask
EF core execute SQL statement
JMeter UDP pressure measurement
The uniapp applet dynamically generates tabbar based on permissions
Redis learning journey -- getting to know redis for the first time
AQS - detailed explanation of reentrantlock source code
MySQL: regexp_ replace
Simple use of logs
思路清晰的软光栅小引擎和四元数结合案例
在排序数组中查找元素的第一个和最后一个位置
Redis learning journey - persistence
不同系统添加证书
18 | 建立数据通路(中):指令+运算=CPU
C语言:如何给全局变量起一个别名?
Selenium reports an error deprecationwarning: executable_ path has been deprecated, please pass in a Service object
Redis master-slave replication - mentality detection mechanism
QT reading SQLSERVER database