简体   繁体   中英

Setting the default `String` value of an object in C#

I'm relatively new to C#, so the concept of default values is somewhat confusing to me.

I currently have an object which contains two String values, serialNumber and fullPath . It's a simple object containing nothing but these two Strings and respective getter methods (they are not to be changed after Object creation; hence the absence of setter methods).

I want to put a List of these objects into a CheckedListBox . I want the box to display only the serial number and not the full path. According to MSDN , the CheckedListBox uses the default String value of the object. How can I set this to serialNumber when the object is created? Again, it should not be changed afterwards. Also, I'm not a big fan of the get and set keywords (I come from a Java background), so if if possible, I'd like to do this with more conventional getters/setters as I've done below for purposes of code readability.

class ModuleData
{

  private String serialNumber;
  private String fullPath;


  public ModuleData(String serialNumber, String fullPath)
  {
     this.serialNumber = serialNumber;
     this.fullPath = fullPath;
  }

  public String getSerialNumber()
  {
     return serialNumber;
  }

  public String getFullPath()
  {
     return fullPath;
  }

  public String toString()
  {
     return serialNumber;
  }

  public String DefaultValue
  {
     return serialNumber;
  }

}

string or String 's default value, default(string) , is null , but that's not what the documentation refers to. It refers to the object's ToString() value, which you can override .

Try something like this, using real C# conventions (look how readable it is!), also notice the override keyword :

public class ModuleData
{
    public ModuleData(string serialNumber, string fullPath)
    {
        SerialNumber = serialNumber;
        FullPath = fullPath;
    }

    public string SerialNumber { get; private set; }

    public string FullPath { get; private set; }

    public override string ToString()
    {
        return SerialNumber;
    }
}

To get the string representation of a class instance you override the ToString method returning your desidered value. In your code you write toString() (lowercase T) and thus being C# case sensitive it is not the correct override.

Just change to

 public override string ToString()
 {
     return serialNumber;
 }

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