使用Property在C#中获取数组元素

kob*_*bra 4 c# arrays properties .net-2.0

有没有办法使用Property从字符串数组中获取特定元素(基于索引).我更喜欢使用公共属性来代替将字符串数组设为public.我正在研究C#.NET 2.0

问候

Joh*_*n K 6

您是否可能尝试保护原始阵列; 你的意思是你想通过"一个属性"(不属于它自己)在阵列周围寻找一个保护性包装?我正在考虑猜测你问题的细节.这是字符串数组的包装器实现.该数组不能直接访问,而只能通过包装器的索引器访问.

using System;

public class ArrayWrapper {

    private string[] _arr;

    public ArrayWrapper(string[] arr) { //ctor
        _arr = arr;
    }

    public string this[int i] { //indexer - read only
        get {
            return _arr[i];
        }
    }
}

// SAMPLE of using the wrapper
static class Sample_Caller_Code {
    static void Main() {
        ArrayWrapper wrapper = new ArrayWrapper(new[] { "this", "is", "a", "test" });
        string strValue = wrapper[2]; // "a"
        Console.Write(strValue);
    }
}
Run Code Online (Sandbox Code Playgroud)


Fre*_*oux 5

如果我正确理解您的要求,您可以使用索引器. 索引器(C#编程指南)

编辑:现在我已经阅读了其他内容,也许你可以公开一个返回数组副本的属性?