简体   繁体   中英

What is the proper way to add different strings to objects in same list?

Following example does not represent the actual class and issue, it has been adapted for various reasons.

I have a List<EnginePart> populated with objects containing byte KeyID, int Length, byte[] Value . Each object was created sequentially and has its own meaning. The list represents "parts to be replaced" and we want to output that to a sales person in a nice format, so he can tell that to the customer. Each part has its own id, lets say 0x20 - cylinder, 0x40 - oil filter.

Now i'd like to add/display a human readable string to each object in a nice way, without iterating through a foreach and checking

if(enginePart.key =="0x20") Console.WriteLine("Cylinder rotation count is " + enginePart.value) .

if(enginePart.key =="0x40") Console.WriteLine("Oil filter only filters " + enginePart.value + " of oil) .

Is there any other, nicer way to do it? Creating a new class for each engine part is not a possibility.

So far I've come up with 3 possible solutions;

1) Iterate through the list and have a bunch of ifs and WriteLines

2) Add a string to the object on creation, but in that case we still have if statements

3) Create some enum and use that on object creation

First I'd suggest you to override the TestClass.ToString() Method, so you won't have to build the string describing the current object in your loop.

See https://docs.microsoft.com/dotnet/api/system.object.tostring?view=netframework-4.7.2

Then maybe the 2nd solution would be quite okay, although we'd need more details on what your goal really is, or have the content of your classes.

Usually when you´re after a "human readable string-representation" you should overwrite ToString :

class EnginePart
{
    byte KeyID { get; set; }
    int Length { get; set; }
    byte[] Value { get; set; }

    public override string ToString()
    {
        return KeyId == "0x40" ? "Oil filter only filters " + value :
               KeyId == "0x20" ? "Cylinder rotation count is " + value :
               ...
    }
}

This way you can rely on the class´ own implementation instead of creating your own in client-code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM