C#中 反射中的Assembly(装载程序集):

反射中的Assembly(装载程序集):可以通过Assembly的信息来获取程序的类,实例等编程需要用到的信息。

1  String assemblyName = @"NamespaceRef";//命名空间
2     String strongClassName = @"NamespaceRef.China";//需要动态生成的类交China

 Assembly.Load(assemblyName).CreateInstance(strongClassName); 

反射用法:利用GetType()动态取实体属性:
GetType():获取当前实例的System.Type.
复制代码
 1 现在有两个类:Student 和 StudentDTO如下:
 2     public class Student
 3     {
 4         public Student()
 5         { 
 6         
 7         }
 8 
 9         public virtual string Id { get; set; }
10 
11         public virtual string StudentNo { get; set; }
12 
13         public virtual string Name { get; set; }
14 
15     }
复制代码
复制代码
 1 public class StudentDTO
 2     {
 3        public StudentDTO()
 4        { 
 5 
 6        }
 7        public virtual string Id { get; set; }
 8 
 9        public virtual string StudentNo { get; set; }
10 
11        public virtual string Name { get; set; }
12 
13        public virtual string ClassId { get; set; }
14 
15      。。。
16     }
复制代码
复制代码
 1 使用GetType()实现实体属性之间赋值:
 2             foreach (var item in student.GetType().GetProperties())    //返回Student的所有公共属性
 3             {
 4                 var value = item.GetValue(student, null);   //返回属性值    
 5                 var setobj = studentDTO.GetType().GetProperty(item.Name);   //搜索具有指定属性名称的公共属性
 6                 if (value != null && setobj != null)
 7                 {
 8                     setobj.SetValue(studentDTO, value, null);
 9                 }
10             } 
复制代码
复制代码
 1 技巧:把方法的参数设置成object类型,就可以一个方法处理多个类型的数据,如下:
 2 public void TypeDemo(object parameter)
 3 {
 4     if(parameter.GetType() == typeof(OtherClass))
 5         {
 6             ....
 7         }
 8  if(parameter.GetType() == typeof(OtherClass1))
 9         {
10             ....
11         }
12  if(parameter.GetType() == typeof(OtherClass2))
13         {
14             ....
15         }
16         ..........
17 }
复制代码

 

 
posted @   Leon_Chaunce  阅读(1946)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示