【问题标题】:How do I access all property variables stored in a C# type? [duplicate]如何访问存储在 C# 类型中的所有属性变量? [复制]
【发布时间】:2023-03-08 00:42:01
【问题描述】:

我想知道是否有一种方法可以确定参数类型中的所有变量及其所有扩展。

例如,如果我有一个叫Kitten的东西

还有Kitten.Name, Kitten.Age Kitten.Type

我如何在不知道它们的情况下访问所有小猫的东西 让他们打印一下这个

"Kitten.Name = Max, Kitten.Age = 4, Kitten.Type = Siamese, Kitten.Owner = Sara"

在这种情况下,我不知道 Sara 是所有者,但现在我知道了,因为我要了所有 Kitten 财产。

【问题讨论】:

  • 反思!看Type.GetProperties()
  • 如果您想要所有数据用于打印目的,请不要使用反射手动循环属性,尽管这样会起作用。使用序列化程序...序列化程序非常适合获取对象结构并将其转换为您可以在其他地方轻松使用的格式。
  • 如何序列化它们?

标签: c# types foreach properties arguments


【解决方案1】:

就像@itsme86 已经提到的......通过反思。


  foreach (PropertyInfo item in userInfo
                .GetType()
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(x => x.CanRead))
            {
                Console.WriteLine($"{item.Name}: {item.GetValue(userInfo, null)}");
            }

【讨论】:

    【解决方案2】:

    您需要查看System.Text.Json 命名空间。它有一个JsonSerializer 类。 Serialize 方法是您需要使用的。在第一步看到有一个作家可能是不直观的,所以让我们看一个例子:

    using System;
    using System.IO;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Text;
    using System.Threading.Tasks;
    namespace DemoApplication
    {
      [Serializable]
      class Tutorial
      {
      public int ID;
      public String Name;
       static void Main(string[] args)
       {
        Tutorial obj = new Tutorial();
        obj.ID = 1;
        obj.Name = ".Net";
    
        IFormatter formatter = new BinaryFormatter();
        Stream stream = new FileStream(@"E:\ExampleNew.txt",FileMode.Create,FileAccess.Write);
    
        formatter.Serialize(stream, obj);
        stream.Close();
    
        stream = new FileStream(@"E:\ExampleNew.txt",FileMode.Open,FileAccess.Read);
        Tutorial objnew = (Tutorial)formatter.Deserialize(stream);
    
        Console.WriteLine(objnew.ID);
        Console.WriteLine(objnew.Name);
    
        Console.ReadKey();
      }
     }
    }
    

    这里将 JSON 写入文件。要使用加载到内存中的 JSON,您需要查看 MemoryStreamSerializeToStream(yourObject)。现在,如果您了解 JSON(如果不了解,请查阅),那么您将能够以能够提取字段的方式解析原始 JSON。阅读本文了解更多信息:https://www.c-sharpcorner.com/article/working-with-json-string-in-C-Sharp/

    您甚至可以在这里找到教程:https://riptutorial.com/csharp/example/32164/collect-all-fields-of-json-object

    【讨论】:

    • 这就像用直升机遛狗一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多