gpt4 book ai didi

c# - 如何使用反射获取对象中的所有变量?

转载 作者:行者123 更新时间:2023-11-30 20:16:05 29 4
gpt4 key购买 nike

我目前正在使用这段代码获取对象中的所有变量并将数据放入字典中(键是变量名,值是变量的内容)。

foreach (var property in PropertiesOfType<string>(propertiesJSON))
{
dictionary.Add(property.Key, property.Value);
}

在这段代码中,propertiesJSON 是我需要的对象。这是 PropertiesOfType 方法:

public static IEnumerable<KeyValuePair<string, T>> PropertiesOfType<T>(object obj)
{
return from p in obj.GetType().GetProperties()
where p.PropertyType == typeof(T)
select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj));
}

当我测试字典中的任何数据时,没有任何值(我使用 Visual Studio 的调试工具进行检查,我的程序还打印出字典中的所有数据 - 当然,不存在)。请告诉我我在这里犯的错误(我还在学习编码,发这篇文章时我才 15 岁)。

编辑:这就是 propertiesJSON 的样子

var propertiesJSON = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.PropertiesJSON>(content);

这是类本身:

class PropertiesJSON
{
public string botToken;
public bool girl;
public int age;
public string[] hi;
public string test;
}

提前致谢。

最佳答案

那些不是属性!

这些:

public string botToken;
public bool girl;
public int age;
public string[] hi;
public string test;

都是字段。如果它们是属性,它们将看起来像这样:

public string botToken { get; }
public bool girl { get; }
public int age { get; }
public string[] hi { get; }
public string test { get; }

要获取字段,请使用 GetFields 而不是 GetProperties

return from p in obj.GetType().GetFields()
where p.FieldType == typeof(T)
select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj));

我建议您将字段更改为所有属性。

关于c# - 如何使用反射获取对象中的所有变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50991916/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com