【问题标题】:How to print the information out of a KeyValuePair<K,T> in C#?如何在 C# 中从 KeyValuePair<K,T> 中打印信息?
【发布时间】:2014-11-29 21:10:20
【问题描述】:

我有一个KeyValuePair&lt;K,T&gt; 的列表。我想打印来自T 的详细信息,但我不知道它的类型以便进行演员表。例如T中存储的值可以是StudentPersonMovie等,我想打印出信息。假设我有p as KeyValuePair,我尝试做p.Value.ToString(),但它只会打印出类型。有没有办法做到这一点?

【问题讨论】:

    标签: c# generics keyvaluepair


    【解决方案1】:

    如果您想在调用时获得有意义的输出,则需要在您的类型中覆盖 ToString 方法。

    您可以在此处找到有关如何操作的详细说明:

    【讨论】:

    • 我怎么没想到呢?非常感谢!
    【解决方案2】:

    您可以使用反射来打印属性值:How to recursively print the values of an object's properties using reflection

    public void PrintProperties(object obj)
    {
        PrintProperties(obj, 0);
    }
    public void PrintProperties(object obj, int indent)
    {
        if (obj == null) return;
        string indentString = new string(' ', indent);
        Type objType = obj.GetType();
        PropertyInfo[] properties = objType.GetProperties();
        foreach (PropertyInfo property in properties)
        {
            object propValue = property.GetValue(obj, null);
            if (property.PropertyType.Assembly == objType.Assembly)
            {
                Console.WriteLine("{0}{1}:", indentString, property.Name);
                PrintProperties(propValue, indent + 2);
            }
            else
            {
                Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
            }
        }
    }
    

    你可以使用反射:C# getting its own class name

    this.GetType().Name

    Selman22 的解决方案是,如果您想真正控制打印内容的输出 - 如果您可以控制所有对象上的 ToString,通常是更好的策略。

    【讨论】:

    • Selman22 的解决方案更简单,更适合我的需求。我也在努力理解你的。谢谢!
    猜你喜欢
    • 2021-04-08
    • 2010-09-21
    • 2021-06-28
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    相关资源
    最近更新 更多