C#类的属性遍历及属性值获取
1、定义一个类
public class Person
{
public string Name { get; set; }
public int ID { get; set; }
}
2、获取属性
方法一、定义一个类的对象获取
Person p = new Person();
foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties())
{
Console.WriteLine(info.Name);
}
方法二、通过类获取
var properties = typeof(Person).GetProperties();
foreach (System.Reflection.PropertyInfo info in properties)
{
Console.WriteLine(info.Name);
}
3、通过属性名获取对象属性值
p.Name = "张三";
var name = p.GetType().GetProperty("Name").GetValue(p, null);
Console.WriteLine(name);
4、完整代码及结果显示
var properties = typeof(Person).GetProperties();
foreach (System.Reflection.PropertyInfo info in properties)
{
Console.WriteLine(info.Name);
}
Console.WriteLine("另一种遍历属性的方法:");
Person p = new Person();
foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties())
{
Console.WriteLine(info.Name);
}
Console.WriteLine("通过属性值获取属性:");
p.Name = "张三";
var name = p.GetType().GetProperty("Name").GetValue(p, null);
Console.WriteLine(name);
Console.ReadLine();
Type t = tc.GetType();//获得该类的Type
//再用Type.GetProperties获得PropertyInfo[],然后就可以用foreach 遍历了
foreach (PropertyInfo pi in t.GetProperties
{
object value1 = pi.GetValue(tc, null));//用pi.GetValue获得值
string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
//获得属性的类型,进行判断然后进行以后的操作,例如判断获得的属性是整数
if(value1.GetType() == typeof(int))
{
//进行你想要的操作
}
}
public int Pid
{
get { return pid; }
set { pid = value; }
}
//****************
public void InitialProperty()//初始化设定
{
System.Reflection.PropertyInfo[] properties = this.GetType().GetProperties();
foreach(var v in properties)
{
string type= v.PropertyType.Name;
if (type=="String")
{
v.SetValue(this,"456",null);
}
else if(type=="Bitmap")
{
v.SetValue(this, new Bitmap(Image.FromFile("1.png")), null);
}
}
}
相关文章
- C#-获取页面源代码
- C#遍历XmlDocument对象所有节点名称、类型、属性(Attribute)
- Extension Methods (C# Programming Guide)
- 如何使用T-SQL备份还原数据库及c#如何调用执行? C#中索引器的作用和实现。 jquery控制元素的隐藏和显示的几种方法。 localStorage、sessionStorage用法总结 在AspNetCore中扩展Log系列 - 介绍开源类库的使用(一) span<T>之高性能字符串操作实测
- 请求大神,C#如何截取字符串中指定字符之间的部分 按指定字符串分割 一分为二 c# 去除字符串中的某个已知字符
- 史上最全的CSS hack方式一览 jQuery 图片轮播的代码分离 JQuery中的动画 C#中Trim()、TrimStart()、TrimEnd()的用法 marquee 标签的使用详情 js鼠标事件 js添加遮罩层 页面上通过地址栏传值时出现乱码的两种解决方法 ref和out的区别在c#中 总结
- C#中泛型方法与泛型接口 C#泛型接口 List<IAll> arssr = new List<IAll>(); interface IPerson<T> c# List<接口>小技巧 泛型接口协变逆变的几个问题
- C# 使用正则表达式去掉字符串中的数字,或者去掉字符串中的非数字
- C#,图像二值化(16)——全局阈值的力矩保持算法(Moment-proserving Thresholding)及其源代码
- C#,最大公共子序列(LCS,Longest Common Subsequences)的算法与源代码
- C# - 时间格式
- C#实现局域网UDP广播--
- C#更改列属性
- c# Format() 方法
- 【C#】C# IO类路径合并、本地路径、拼接路径Path.Combine
- c# 根据字段名,得到对象中的属性值
- c#生成MD5字符串
- 《C#零基础入门之百识百例》(五十六)多态介绍 -- 简单工厂模式
- C# 面向对象(封装 — 属性)
- java 调用 C# webapi
- C#反射设置属性值和获取属性值
- C#属性默认值设置
- C# 特性参数(注解属性加在参数前面)
- C#在方法或属性中使用sealed时的操作与原理
- C#基础 字段、属性、变量三者的关系
- C# 操作IIS方法集合