目录常规属性属性PropertyInfo的使用在C#中,PropertyInfo是一个用于获取和设置属性的类。可以使用以下方式来使用PropertyInfo:
1.获取属性的Type:
可以使用PropertyInfo的PropertyType属性来获取属性的类型。例如,如果有一个名为"Name"的属性,可以使用以下代码获取属性的类型:PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("Name");Type propertyType = propertyInfo.PropertyType;
2.获取属性的值:
可以使用PropertyInfo的GetValue方法来获取属性的值。需要提供一个对象实例作为参数,表示从该对象中获取属性的值。例如:ExampleClass example = new ExampleClass();example.Name = "John";PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("Name");object propertyValue = propertyInfo.GetValue(example);
3.设置属性的值:
可以使用PropertyInfo的SetValue方法来设置属性的值。需要提供一个对象实例和要设置的值作为参数。例如:ExampleClass example = new ExampleClass();PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("Name");propertyInfo.SetValue(example, "John");这些是PropertyInfo的一些基本用法。还可以使用其他方法和属性来进行更高级的操作,例如获取和设置属性的访问修饰符、属性的特性等。
常规属性
看下常规属性的完成构成:
1.私有字段,一般设置为私有,通过属性来赋值保证起安全性:
private string _age;2.get访问器,负责读取数据,其中可以进行自己的逻辑判断和数据验证,以return或者throw结束:自动属性上面简单的说了一下常规属性,当属性访问器中不需要其他逻辑时,可以使用自动属性,public int Id { get; set; }简单的对比一下常规属性和自动属性之间的区别吧:1.自动实现的属性必须同时声明 get 和 set 访问器。创建 readonly 自动实现属性时,需要将set 访问器设置为private 。
2自动实现的属性上可以使用特性,不能用在支持后备字段上。 如果属性的后备字段上使用特性,则应该只创建常规属性。
3.自动实现属性get,和set中不能包含特殊的逻辑处理。与字段类似,但不同于字段。与字段不同,属性不作为变量来分类,不能将属性作为 ref参数或 out参数传递。
属性PropertyInfo的使用
定义Person类:
public class Person {public Person(int id,string name,string address){this.Id = id;this.Name = name;this.Address = address;}public int Id { get; set; }public string Name { get; set; }public string Address { get; set; }}定义User类public class User {public int Id { get; set; }public string Name { get; set; }public string Group { get; set; }}
转换方法:
public static User ConvertObject(User user,Person person){PropertyInfo[] userPro = user.GetType().GetProperties();PropertyInfo[] personPro = person.GetType().GetProperties();if (userPro.Length>0&&personPro.Length>0){for (int i = 0; i < userPro.Length; i++){for (int j = 0; j < personPro.Length; j++){方法的调用:
//判断User的属性是不是的Person中if (userPro[i].Name == personPro[j].Name && userPro[i].PropertyType == personPro[j].PropertyType){Object value=personPro[j].GetValue(person, null);//将Person中属性的值赋值给User
userPro[i].SetValue(user,value , null);}}}}return user;}static void Main(string[] args){Person person = new Person(1,"FlyElephant","北京");User user = new User();user.Id = 20;user = ConvertObject(user, person);Console.WriteLine("Id:" + user.Id + "Name:" + user.Name + "角色:" + user.Group);System.Console.Read();}2.之前在做Winform的时候就经常回使用到SqlHelper,现在也有很多公司是这么使用的,当时很多东西感觉就是重复性的操作,一度以为编程只是复制粘贴,下面这段代码大家应该很常见:List开始写的时候觉得是锻炼了,写的多了就觉得无聊了,其实完全可以换一种方式来实现上面的代码:public static ListList到此这篇关于C#中属性PropertyInfo怎么使用的文章就介绍到这了,更多相关C# PropertyInfo使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:C# PropertyInfo类案例详解C# 中属性PropertyInfo的setvalue用法说明
