如何将 PropertyInfo[] 转换为我的 class

How to convert PropertyInfo[] to my class

我正在开发 .NET Core 3.1 API,我遇到过需要使用 foreach 迭代对象的情况。为了能够做到这一点,我使用了 Reflection:

var properties = myClass.GetType().GetProperties();

之后,代码正常通过 foreach,然后我 return 修改后的 properties 对象到外部 API,但是它return 是超时错误消息,我认为这是因为 PropertyInfo[] class 不太适合这样 returning,或者是别的,我不知道。

因此,我想将 properties“返回”到 myClass,或者可能将其转换成字典,它会最好是 return 原来的 class 而不是 PropertyInfo[].

如何将 PropertyInfo[] 转换为 class?

谢谢!

听起来您正在尝试将此 class 序列化以发送到 API。您的 API 接受什么格式?如果它接受例如json,你应该只使用 json 序列化器(比如 JSON.net - 它在底层使用反射之类的东西)。如果您正在尝试序列化为更奇特或不受支持的格式,那么您可以这样做。缺少的是 Properties[] 数组不包含属性的值,仅包含定义。您可以使用属性数组来获取值:

public class MyClass
{
    public int a { get; set;}
    public string b {get; set; }
}

void Main()
{
    var instance = new MyClass{a=1,b="2"};
    var properties = instance.GetType().GetProperties();
    var value_of_a = properties.First(p => p.Name == "a").GetValue(instance);
}

每个 属性 都有一个“GetValue”方法,可以从 属性 来自的 class 中提取对应于 属性 的值 - 请注意在你调用 'GetProperties' 之前调用 'GetType()' - 这意味着你正在获取类型的属性,而不是实例。然后,您需要将这些 属性 定义带回实例以获取 属性 值。