C#使用IEnumerator迭代嵌套属性

问题描述 投票:0回答:2

我已经在列表和数组或字典上看到了IEnumerator的示例(和官方示例),但是我有一个不同的问题。我有带有属性的类,在这种情况下如何实现IEnumerable和IEnumerator?

我的属性类是:

public class standardMessage
{
    public messageProperties message { get; set; }
    public messageFlag flag { get; set; }
}

public class messageProperties
{
    public string messageSubject { get; set; }
    public string messageBody { get; set; }
}

public class messageFlag
{
    public Boolean flagImportant { get; set; }
    public Boolean flagPersonal { get; set; }
}

这是程序:

public class Program
{
    static void Main(string[] args)
    {
        standardMessage myMessage = new standardMessage();

        myMessage.message = new messageProperties
        {
            messageSubject = "Greetings",
            messageBody = "Happy Weekend"
        };

        myMessage.flag = new messageFlag
        {
            flagImportant = false,
            flagPersonal = true
        };

        //how do I iterate through all properties, without knowing how many are there, instead of writing this worm line of code?
        Console.WriteLine(myMessage.message.messageSubject.ToString() + "\r\n" + myMessage.message.messageBody.ToString() + "\r\n" + myMessage.flag.flagImportant.ToString() + "\r\n" + myMessage.flag.flagPersonal.ToString());
        Console.ReadLine();
    }
}
c# properties ienumerable ienumerator
2个回答
0
投票

如果要以生产级的方式将对象打印为格式化字符串,则需要遍历所有类中的ToString以返回所需的任何格式。

但是,如果您只是想在屏幕上打印内容以进行调试或记录,为什么不使用JSON?

public static string ToJson(object @object) =>
    System.Text.Json.JsonSerializer.Serialize(@object, new JsonSerializerOptions{WriteIndented = true});
Console.WriteLine(ToJson(myMessage));

打印

{
  "message": {
    "messageSubject": "Greetings",
    "messageBody": "Happy Weekend"
  },
  "flag": {
    "flagImportant": false,
    "flagPersonal": true
  }
}

快速又肮脏,但是又快速又有效。


0
投票

我对json转换器做了一个非常原始的对象。我不会在生产中使用它,它比Newtonsoft慢30%,但可以完成工作。

private static string PrintObject(object obj, int depth = 1)
{
    var type = obj.GetType();
    if (type.IsPrimitive || type == typeof(Decimal) || type == typeof(String))
        return "\"" + obj.ToString() + "\"";
    var props = type.GetProperties();
    string ret = "";
    for (var i = 0; i < props.Length; i++)
    {
        var val = props[i].GetValue(obj);
        ret += new string('\t', depth) + "\"" + props[i].Name + "\":" + PrintObject(val, depth + 1);
        if (i != props.Length - 1)
            ret += "," + Environment.NewLine;
    }

    return ("{" + Environment.NewLine + ret + Environment.NewLine + new string('\t', depth - 1) + "}").Replace("\t", "  ");
}

给出结果

{
  "message":{
    "messageSubject":"Greetings",
    "messageBody":"Happy Weekend"
  },
  "flag":{
    "flagImportant":"False",
    "flagPersonal":"True"
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.