大学选修课网站建设,做运营必看的网站,天辰建设网,证件照制作免费版文章目录 前言反射是什么#xff1f;常用类型操作SummryPropertyInfoMethodInfo无参函数运行 有参函数运行,获取paramterInfo 总结 前言
我之前写了一篇Attribute特性的介绍#xff0c;成功拿到了Attribute的属性#xff0c;但是如果把Attribute玩的溜#xff0c;那就要彻… 文章目录 前言反射是什么常用类型操作SummryPropertyInfoMethodInfo无参函数运行 有参函数运行,获取paramterInfo 总结 前言
我之前写了一篇Attribute特性的介绍成功拿到了Attribute的属性但是如果把Attribute玩的溜那就要彻底了解反射。 C#高级语法 Attribute特性详解和类型方法变量附加特性讲解 反射是什么
反射就是对一个类里面所有的元素的彻底描述。我们可以从特性看出C# 对基于反射的类型定义了。 【C#进阶】C# 特性 我们声明一个简单的类 namespace NETCore8.Models
{public class TestModel{public int Id { get; set; }private string name;public void Send(){}/// summary/// 发送测试/// /summary/// param namename/parampublic void TestSend(string name){}public TestModel(){}}
}常用类型操作 我们接下来的操作全部都是基于共有属性进行的操作 Summry
但是Summry不属于编译内容属于注解如果想要获取Summry信息则需要安装一个NugetNamotion.Refelction PropertyInfo static void Main(string[] args){//声明一个简单的bindingFlagsBindingFlags bindingFlags BindingFlags.Public | BindingFlags.Instance;TestModel model new TestModel();model.Id 5;var propertyInfo model.GetType().GetProperty(Id);Console.WriteLine(属性名: propertyInfo?.Name);Console.WriteLine(属性值: propertyInfo?.GetValue(model));Console.WriteLine(属性类型: propertyInfo?.PropertyType);propertyInfo.SetValue(model, 10);Console.WriteLine(修改后的属性值: propertyInfo.GetValue(model));//如果你安装了Namotion.Refelction,可以使用封装好的扩展方法Console.WriteLine(Namotion.Refelction: model.TryGetPropertyValueint(Id));Console.WriteLine(Hello, World!);Console.ReadKey();}MethodInfo
无参函数运行 static void Main(string[] args){TestModel model new TestModel();var methodInfo model.GetType().GetMethod(Send);if (methodInfo ! null){Console.WriteLine($方法名:{methodInfo.Name});Console.WriteLine($返回值:{methodInfo.ReturnType});Console.WriteLine(运行方法);methodInfo.Invoke( model, null );}Console.WriteLine(Hello, World!);Console.ReadKey();}有参函数运行,获取paramterInfo internal class Program
{static void Main(string[] args){TestModel model new TestModel();var methodInfo model.GetType().GetMethod(TestSend);//如果你装了Namotion.Refelction可以使用Xml方法获取注解if (methodInfo! null ){Console.WriteLine($方法名:{methodInfo.Name});Console.WriteLine($返回值:{methodInfo.ReturnType});Console.WriteLine($方法注解:{methodInfo.GetXmlDocsSummary()});var parmeters methodInfo.GetParameters();foreach (var item in parmeters){Console.WriteLine($参数名:{item.Name});Console.WriteLine($参数类型:{item.ParameterType});Console.WriteLine($参数注解:{item.GetXmlDocs()});}Console.WriteLine(运行方法注意无法解决重载问题因为重载的方法名相同,会直接抛出异常);Console.WriteLine(运行方法的参数类型和个数必须完全一致);methodInfo.Invoke(model, new object[] { 入参,1 });}Console.WriteLine(Hello, World!);Console.ReadKey();}
}总结
我们将反射类型的常用内容已经讲解完了。接下来我们将主要讲解Attribute的详细运用。经过这么久的铺垫我们终于可以开始正常的讲解了。