Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当我需要数组在C中有一个间隔时,如何处理数组属性?_C#_Arrays_Properties_Setter_Getter - Fatal编程技术网

C# 当我需要数组在C中有一个间隔时,如何处理数组属性?

C# 当我需要数组在C中有一个间隔时,如何处理数组属性?,c#,arrays,properties,setter,getter,C#,Arrays,Properties,Setter,Getter,我对C语言非常陌生,我仍在努力了解它的一些核心概念。第一次向StackOverflow发帖 这就是我需要帮助的地方: 为:私有字符串数组;创建属性:以便: 数组的每个元素都需要>=0,并查看这是否是您需要的: 你在找这样的东西 private int[] _privateArray; public int[] PublicArray { get { return _privateArray; } set { foreach

我对C语言非常陌生,我仍在努力了解它的一些核心概念。第一次向StackOverflow发帖

这就是我需要帮助的地方:

为:私有字符串数组;创建属性:以便:
数组的每个元素都需要>=0,并查看这是否是您需要的:


你在找这样的东西

private int[] _privateArray;
public int[] PublicArray
{
    get
    {
        return _privateArray;
    }
    set
    {
        foreach (int val in value)
        {
            if (val < 0 || val > 10) throw new ArgumentOutOfRangeException();
        }
        // if you get to here you can set value
        _privateArray = (int[])value.Clone();
    }
}

请注意,私有属性和公共属性必须是同一类型

C为强类型。为什么有一个包含数字的字符串数组?仅0到10之间的数字应存储为字节。你能解释一下你想做什么吗?一个属性只能检查整个数组的赋值,但是如果有人给数组位置赋值,它将不会被激活。课文没有说更多吗?这个物业也可以是一个酒店吗?因为索引器允许您检查分配到任何数组位置的有效性。请注意,即使您验证每个元素当前都在[0,10]范围内,也不会阻止数组在之后发生变异,除非您克隆它。是的,规范不清楚。整个数组是可分配的还是只读的并在内部创建的?这并没有多大帮助,因为数组可以在以后进行变异。其他选项是剪裁值Math.Max0、Math.Min10或抛出异常。同样,规范也非常不明确。
public class myClass
{
    private int[] _Array = new int[10];

    public int this[int index]
    {
        get { return _Array[index]; }
        set
        {
            if (value >= 0 && value <= 10)
                _Array[index] = value;
        }
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        myClass m = new myClass();
        m[0] = 1;
        m[1] = 12;
        Console.WriteLine(m[0]); // outputs 1
        Console.WriteLine(m[1]); // outputs default value 0
    }
}
private int[] _privateArray;
public int[] PublicArray
{
    get
    {
        return _privateArray;
    }
    set
    {
        foreach (int val in value)
        {
            if (val < 0 || val > 10) throw new ArgumentOutOfRangeException();
        }
        // if you get to here you can set value
        _privateArray = (int[])value.Clone();
    }
}