2009-10-21 61 views
3

是否有一种方法可以使用Property从字符串数组中获取特定元素(基于索引)。我更喜欢使用公共属性来取代公开的字符串数组。我在C#.NET 2.0使用属性获取C#中的数组元素

问候

回答

6

如果我正确理解你在问什么,你可以使用索引器。 Indexers (C# Programming Guide)

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

+0

我不想返回整个字符串数组的副本,只是数组的一个元素。我认为索引会有所帮助。谢谢 – kobra 2009-10-21 21:32:43

4

工作如果财产公开数组:

string s = obj.ArrayProp[index]; 

如果你的意思是“我能有一个索引属性”,则没有 - 但你可以有属性是一个索引器类型:

static class Program 
{ 
    static void Main() 
    { 
     string s = ViaArray.SomeProp[1]; 
     string t = ViaIndexer.SomeProp[1]; 
    } 
} 
static class ViaArray 
{ 
    private static readonly string[] arr = { "abc", "def" }; 
    public static string[] SomeProp { get { return arr; } } 
} 
static class ViaIndexer 
{ 
    private static readonly IndexedType obj = new IndexedType(); 
    public static IndexedType SomeProp { get { return obj; } } 
} 
class IndexedType 
{ 
    private static readonly string[] arr = { "abc", "def" }; 
    public string this[int index] 
    { 
     get { return arr[index]; } 
    } 
} 
+0

对不起,我的意思是类似于公共字符串[]名称{得到{返回_名称[索引]; }} – kobra 2009-10-21 21:22:47

3

你需要的是一个可以有输入(一个索引)的属性。

只有一个这样的属性,称为索引器。

在MSDN上查找它。

快捷键:使用内置的代码片段:转到您的班级并键入'indexer',然后按两次选项卡。中提琴!

1

我假设你有一个具有私有字符串数组的类,并且你希望能够获取数组的一个元素作为你的类的属性。

public class Foo 
{ 
    private string[] bar; 

    public string FooBar 
    { 
     get { return bar.Length > 4 ? bar[4] : null; } 
    } 
} 

这似乎可怕的哈克,虽然如此,我现在不是不明白你想要什么,或者可能有一个更好的方式做你想做的,但我们需要知道更多的信息。

更新:如果您在注释中指明了某个元素的索引,那么可以使用索引器或简单地创建一个获取索引并返回该值的方法。我会保留一个本身就是一个容器的类的索引器,否则使用方法路由。

public string GetBar(int index) 
{ 
    return bar.Length > index ? bar[index] : null; 
} 
+0

我可以看到从预构建的CSV解析器返回的字符串数组,并且想构建一个简单的对象来包装该数组的内容。但将字符串复制到支持商店可能更好,因为它们只是引用。 – 2009-10-21 21:25:37

+0

对不起,如果我困惑你。我真的想要使用另一个类的字符串数组中的索引来获取特定元素,而不需要公开字符串数组。所以我想用公共财产。谢谢 – kobra 2009-10-21 21:30:16

0

只需从属性返回数组;结果对象将表现为一个数组,因此您可以对其进行索引。

例如为:

string s = object.Names[15] 
1

属性不带参数,这样就不会成为可能。

您可以构建一个方法,例如

public string GetStringFromIndex(int i) 
{ 
    return myStringArray[i]; 
} 

,你可能会想要做一些检查方法。当然,但你的想法。

4

你可能试图保护原始数组;你的意思是你想要通过“一个财产”(而不是自己的)一个保护性包装阵列?我正在拍摄这个镜头来猜测你的问题的细节。这是一个字符串数组的包装器实现。数组不能直接访问,但只能通过包装器的索引器。

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