解释:上面看不懂可以这里,我用简单举例來解释什么是反射,比如我们写了一个web api接口接收到的不知道是什么类型的数据,不明确数据源数据类型,但是我们要去里面拿到我们想要的属性 数据,当然反射还有别的用法,刚才只是简单举例
代码示例
首先我们要用
.GetType(); //获取类型
然后用
.GetProperties();//获取所有公共属性
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
internal class Program
{
static void Main(string[] args)
{
Model model = new Model();
model.Name = "张三";
model.Sex = "未知";
//比如我们不明确model是什么数据类型,不明确里面有什么属性
var type=model.GetType(); //获取类型
var props=type.GetProperties();//获取所有公共属性
foreach(PropertyInfo item in props)
{
var value=item.GetValue(model); //获取值
Console.WriteLine($"Name:{item.Name}Value:{value}");//输出属性,和值
}
}
}
public class Model
{
public string Name { get; set; }
public string Sex{ get; set; }
}
}
运行结果
方法
GetMember(),GetMembers()
1.返回MemberInfo类型,用于取得该类的所有成员的信息
2.GetConstructor(),GetConstructors() -返回ConstructorInfo类型,用于取得该类构造函数的信息
GetEvent(),GetEvents()
返回EventInfo类型,用于取得该类的事件的信息
GetInterface(),GetInterfaces()
返回InterfaceInfo类型,用于取得该类实现的接口的信息
GetField(),GetFields()
返回FieldInfo类型,用于取得该类的字段(成员变量)的信息
GetPropeerty(),GetProperties()
返回ProperyInfo类型,用于取得该类的属性的信息
GetMethod(),GetMethods()
返回MethodInfo类型,用于取得该类的方法的信息
///获取对象属性值方法封装/// 利用反射来判断对象是否包含某个属性 /// /// object /// 需要判断的属性 ///是否包含 public static bool ContainProperty(this object instance, string propertyName) { if (instance != null && !string.IsNullOrEmpty(propertyName)) { PropertyInfo _findedPropertyInfo = instance.GetType().GetProperty(propertyName); return (_findedPropertyInfo != null); } return false; }
///获取属性列表方法封装/// 获取对象属性值 /// ////// /// /// public static string GetObjectPropertyValue (T t, string propertyname) { Type type = typeof(T); PropertyInfo property = type.GetProperty(propertyname); if (property == null) { return string.Empty; } object o = property.GetValue(t, null); if (o == null) { return string.Empty; } return o.ToString(); }
////// 获取属性列表 /// ///public static void GetObjectProperty () { Type t = typeof(T); System.Reflection.PropertyInfo[] properties = t.GetProperties(); foreach (System.Reflection.PropertyInfo info in properties) { Console.Write("name=" + info.Name + ";" + "type=" + info.PropertyType.Name + ";value=" + GetObjectPropertyValue



