如何使用System.Reflection确定属性是否是我定义的类之一

如何解决如何使用System.Reflection确定属性是否是我定义的类之一

根据此示例:

public class a
{
    public string a1 {get; set;} = "va1";
    public int a2 {get; set;} = 20;
}

public class b
{
   public string b1 {get; set;} = "vb1";
   public int b2 {get; set;} = 40;
}

public class c
{
    public string c1 {get; set;} = "vc1";
    public int c2 {get; set;} = 60;
    public a class_a {get; set;} = new a();
    public b class_b {get; set;} = new b();
}

我正在尝试构建一种递归返回所有属性值的方法,在本例中为class c,但我想使其对任何其他类通用。

static void GetValues(Object obj)
{
    Type t = obj.GetType();
    PropertyInfo[] properties = t.GetProperties();
    foreach (var property in properties)
    {
        if (property.PropertyType.Name == "a" || property.PropertyType.Name == "b")
        {
            Console.WriteLine($"--- Properties class: {property.PropertyType.Name} ---");
            GetValues(property.GetValue(obj,null));
        }
        else
        {
            Console.WriteLine($"Type: {property.PropertyType.Name}  {property.Name} = {property.GetValue(obj,null).ToString()}");
        }
    }
}

该函数返回以下结果:

Type: String  c1 = vc1
Type: Int32  c2 = 60
--- Properties class: a ---
Type: String  a1 = va1
Type: Int32  a2 = 20
--- Properties class: b ---
Type: String  b1 = vb1
Type: Int32  b2 = 40

问题

是否有一种方法可以知道某个属性是否为class类型,而不是专门针对类ab进行检查?

我想替换以下代码行:

if (property.PropertyType.Name == "a" || property.PropertyType.Name == "b")

通过类似的方式:

if (property.IsClass)

我已在 Rextester

上设置了此示例

解决方法

您就在那儿-您只需要记住您是否在询问属性类型是否是一类:

if (property.PropertyType.IsClass)
,

使用反射,您可以查询任何类型的属性。请注意,结构也可能具有属性。因此,递归所有类型而不仅仅是类都是有意义的。

但是请注意,这对于某些内置类型(例如具有string属性的Length和具有许多DateTime和{{1 }}。更糟糕的是,它的属性DayOfWeek再次是Ticks,从而创建了无限递归。因此,通过尝试一个错误,您可能必须排除某些类型,甚至实现检测递归的机制,或者至少限制最大嵌套级别。

以下是排除示例:

Date

调用DateTime的结果
(我添加了private static readonly HashSet<Type> ExcludedTypes = new HashSet<Type> { typeof(string),typeof(DateTime) }; static void GetValues(Object obj,int level) { Type t = obj.GetType(); PropertyInfo[] properties = t.GetProperties(); foreach (var property in properties) { if (property.GetIndexParameters().Length == 0) { // Exclude indexers Console.Write(new string(' ',4 * level)); Type pt = property.PropertyType; object value = property.GetValue(obj,null); Console.WriteLine($"{pt.Name} {property.Name} = {value}"); if (value != null && !ExcludedTypes.Contains(pt)) { GetValues(value,level + 1); } } } } GetValues(new c(),0);属性以使其更加有趣):

DateTime a3

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res