question about print List<T> to screen

人走茶凉 提交于 2021-02-10 14:21:05

问题


A question about List;

alt text When i have "List<PlugwiseMessage> msg" with the value's from the picture :

I only get PlugwiseLib.BLL.BC.PlugwiseMessage as output.

But how can i see the value's from _message, _owner and _type on my screen ? or the value's of Message, Owner, and Type?

And can somebody explain the difference to me ?


回答1:


Your list has a collection of PlugwiseLib.BLL.BC.PlugwiseMessage objects. Message, Owner and Type are properties on the object. The _message, _owner and _type variables are the backing fields that are exposed by the properties.

When you are doing the console output, you are calling .ToString() on the PlugwiseMessage object. The default behavior of ToString() is to print the name of the object. If you want to display the properties you will need to add several lines

Console.WriteLine(msg[i].Message);
Console.WriteLine(msg[i].Owner);
Console.WriteLine(msg[i].Type);



回答2:


The problem is that you're printing the object itself and not the properties, so it uses the default ToString() method which returns the object's type's name.

There's one of two options. You can override the ToString() method in the class PluginwiseMessage to return a formatted string with the info you want or if you don't have access to that you can do the following:

foreach(PluginwiseMessage message in msg)
{
    Console.WriteLine("{0} {1} {2}", message.Message, message.Owner, message.Type);
    Console.Read();
}

You can easily rearrange the parameters being printed and add more text to the output, but that will simply output Message, Owner, and Type separated by spaces.




回答3:


Your list contains PlugwiseMessage objects and you tell Console to write them down. To do that PlugwiseMessage instances have to converted into a string. ToString() is used to do that and the default implementation just dumps the name of the type. That's what you observe.

If it's possible, you should override the ToString method and adjust it to your needs. If that's not possible, you have to dump the values by yourself. That means you have to pass msg[i].Messasge, msg[i].Owner, ... to WriteLine().




回答4:


overide ToString method in PlugWiseMessage type.

public override string ToString()
        {
            return String.Format("Owner {0}, Message {1}, Type {2}", this.Owner, this.Message, this.Type);
        }



回答5:


msg[i].Message
msg[i].Owner
msg[i].Type


来源:https://stackoverflow.com/questions/4700792/question-about-print-listt-to-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!