在c#内部类中获取数组属性的长度,或者其他有效的迭代方法

本文关键字:或者 其他 有效 方法 迭代 内部类 获取 数组 属性 | 更新日期: 2023-09-27 18:09:02

我有一组由json2charp web实用程序从REST调用产生的JSON响应生成的c#类。我使用这些类将未来的JSON响应反序列化到这些类中。一切都很好。其中一个内部类有一个数组属性。我试图使用数组的Length属性在for循环中使用该属性,但Length属性在当前范围内不可用。我猜这是因为它是一个内部类?

为了解决这个问题,我添加了一个名为CountBreeds的公共属性,它只返回数组长度。这很好。但我想知道是否有一种方法来获得内部类的数组属性的长度,而不必使属性只是为了暴露数组的长度属性?如果没有,有没有一种方法来迭代数组而不添加IEnumerable支持类?

我知道我可以删除"内部"说明符,但如果可以的话,我想保留它。以下代码片段:

// 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);

在c#内部类中获取数组属性的长度,或者其他有效的迭代方法

您要求的不是数组的长度,而是在breed类中不存在的length属性。

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

长度应该可见。Length是Array的公共属性,因此它与内部类无关。

相关文章: