Domanda

I have to realize a serializazion/deserialization class and i'm using System.Xml.Serialization. I have some IList<Decimal> type properties and wanted to serialize in IList<string> decoding all decimal value belonging to the list with a specific culture info. For example 10 is 10,00 with Italian culture info but 10.00 with English culture info. I tried to do it using this:

public IList<string> method()
    {
        for (int i = 0; i < 1000; i++)
        {
            yield return i.ToString();
        }
    }   

But i get at compile time Error 33

The body of 'Class1.method()' cannot be an iterator block because 'System.Collections.Generic.IList<string>' is not an iterator interface type

If i use as property type IEnumerable<string> it works succesfully but obviusly i can't change the type of data i want to serialize .

Any help is appreciated.

È stato utile?

Soluzione

yield only works with IEnumerable<T>, IEnumerable, IEnumerator<T> and IEnumerator as return type.
In your case, you need to use a normal method instead:

public IList<string> method()
{
    var result = new List<string>();
    for (int i = 0; i < 1000; i++)
    {
        result.Add(i.ToString());
    }
    return result;
}

Think about it. Your code would allow you to write the following code:

method().Add("foo");

That doesn't make too much sense, does it?

Altri suggerimenti

You can also move the iterator block to a private method or getter, like this:

public IList<string> method()
{
  return seq.ToList();
}

IEnumerable<string> seq
{
  get
  {
    for (int i = 0; i < 1000; i++)
    {
      yield return i.ToString();
    }
  }
}

But also note that for the particular case of a range x : x+1 : x+2 : ... : x+(n-1) there's already in .NET the method Enumerable.Range which you could use like this:

public IList<string> method()
{
  return Enumerable.Range(0, 1000).Select(i => i.ToString()).ToList();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top