前言:反射提供描述程序集、模块和类型的对象(Type 类型)。 可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型,然后调用其方法或访问器字段和属性。 如果代码中使用了特性,可以利用反射来访问它们。
解释:上面看不懂可以这里,我用简单举例來解释什么是反射,比如我们写了一个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类型,用于取得该类的方法的信息
利用反射来判断对象是否包含某个属性的实现方法封装
/// <summary>
/// 利用反射来判断对象是否包含某个属性
/// </summary>
/// <param name="instance">object</param>
/// <param name="propertyName">需要判断的属性</param>
/// <returns>是否包含</returns>
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;
}
获取对象属性值方法封装
/// <summary>
/// 获取对象属性值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="propertyname"></param>
/// <returns></returns>
public static string GetObjectPropertyValue<T>(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();
}
获取属性列表方法封装
/// <summary>
/// 获取属性列表
/// </summary>
/// <typeparam name="T"></typeparam>
public static void GetObjectProperty<T>()
{
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<Object>(new object(), info.Name) + "<br />");
}
}