Вопрос

I have a set of C# classes generated by the json2charp web utility from a JSON response resulting from a REST call. I use the classes to deserialize future JSON responses into those classes. Everything works great. One of the internal classes has a property that is an array. I tried to use the property in a for-loop using the array's Length property but the Length property is unavailable in the current scope. I'm guessing this is because it is an internal class?

To work around the problem I added a public property called CountBreeds that just returns the array Length. That works fine. But I'm wondering if there is a way to get the Length of an internal class's array property without having to make properties just to expose the Length property of the array? If not, is there a way to iterate the array without adding IEnumerable support to the class?

I know I could remove the "internal" specifier but I'd like to keep it if I can. Code snippets below:

// The internal class I want to iterate.
internal class Breeds
{

    [JsonProperty("breed")]
    public Breed[] Breed { get; set; }

    [JsonProperty("@animal")]
    public string Animal { get; set; }

    // This property was added to facilitate for loops-that iterate the
    //  entire array, since the Length propery of the array property
    //  can not be accessed.
    public int CountBreeds
    {
        get
        {
            return Breed.Length;
        }
    }
} // internal class Breeds

// Code that iterates the above class.

// >>>> This doesn't work since the Breeds Length property
//  is unavailable in this context.
//
// Add the breeds to the list we return.
for (int i = 0; i < jsonPF.Petfinder.Breeds.Length; i++)
    listRet.Add(jsonPF.Petfinder.Breeds.Breed[i].T);


// >>>> This *does* work because I added manually the CountBreeds
//  property (not auto-generated by json2csharp).
// Add the breeds to the list we return.
for (int i = 0; i < jsonPF.Petfinder.Breeds.CountBreeds; i++)
    listRet.Add(jsonPF.Petfinder.Breeds.Breed[i].T);
Это было полезно?

Решение

You weren't asking for the length of the array, but for a non-existent Length property in the Breeds class. Try this instead...

for (int i = 0; i < jsonPF.Petfinder.Breeds.Breed.Length; i++)

Другие советы

Length should be visible. Length is a public property on Array, so it has nothing to do with the internal class.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top