开发者

IEnumerable of Custom class and String.Join()

开发者 https://www.devze.com 2023-01-31 10:45 出处:网络
I\'ve created a class which acts as an all-purpose DataType class. I am doing this because I need to serialize a collection of misc-typed objects to JSON, and I\'d like to be able to create the full d

I've created a class which acts as an all-purpose DataType class. I am doing this because I need to serialize a collection of misc-typed objects to JSON, and I'd like to be able to create the full data set as a collection. Like so:

JSON.Serialize(new []
{
    new Chameleon("aDate", DateTime.Now),
    new Chameleon("aString", "FUBAR")
});

The following is a simplified version of my implementation:

class Chameleon
{
    private String _typ开发者_开发知识库e;
    private String _key;
    private Object _value;

    public Chameleon(String key, String value)
    {
        _type = "string";
        _key = key;
        _value = value;
    }

    public Chameleon(String key, DateTime value)
    {
        _type = "string";
        _key = key;
        _value = value;
    }

    public new String ToString()
    {
        // returns internal data, formatted data according to _type
    }
}

This is all well and good, but when I try and join - or concatinate if you will - a collection of Chameleon using String.Join(), ToString() on Chameleon objects in the collection are not called by the String.Join() method; instead I get the usual namespace + class-name string returned.

Why is String.Join() not calling my custom ToString() implementation? What am I missing?

Here's what I'm doing:

JSON.Serialize(String.Join<Chameleon>(",", new []
{
    new Chameleon("aDate", DateTime.Now),
    new Chameleon("aString", "FUBAR")
}));


My guess is that this occurs because you define ToString as a new method, rather than overriding it. Try this code instead:

public override String ToString()
{
    // returns internal data, formatted data according to _type
}


That was it. Try defining your ToString like this:

  public override String ToString() //Note the override rather than new
  {
    //Format your string etc.
  }


You need to put ToString on each Chameleon object otherwise you have an array of Chameleon object instead of an array of string which should be used.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号