代码之家  ›  专栏  ›  技术社区  ›  Jasmeet

将多维数组属性公开为公共的最佳方法?

  •  0
  • Jasmeet  · 技术社区  · 6 年前

    我需要实现一个多维数组作为公共属性。

    public int[][] ArrayProperty
    {get; set;}
    

    但是,它给了我一个代码分析错误-“CA1819:PropertiesShouldNotReturnArrays”

    所以我想把它改成一个嵌套列表,比如:

    public List<List<int>> ArrayProperty
    {get;set;}
    

    但我很肯定它会给出另一个代码分析错误,即不要嵌套泛型类型。

    如何更新我的属性结构,使其具有最佳的实现以满足我的需求?

    3 回复  |  直到 6 年前
        1
  •  1
  •   usr    6 年前

    NET框架通常通过创建一个自定义集合类来解决这个问题。这样可以验证数据,提供自定义方法,并且类型名可以使代码更易于理解。

    class MyCollection : IList<int[]> { ... }
    

    你甚至可以走得更远,把它包起来 int[]

    //alterantively add an indexer instead of exposing the array
    class MyThing { public int[] MyValues { get; set; } }
    
    class MyCollection : IList<MyThing> { ... }
    

    这可能是一个很大的工作。如果你正在写一个库供其他人使用,这可能是值得的努力。如果是内部代码,我会选择任何方便的。您可以稍后更改它,因为您正在控制所有呼叫者。

        2
  •  0
  •   Jayanta Patra    6 年前
    1. List<KeyValuePair<string, string>>
    2. Dictonary<string, Dictonary<string,string>>
    

        3
  •  0
  •   FeelaV    6 年前

    “属性不应返回数组。”

    Microsoft文档参考 here

    using System;
    using System.Collections.ObjectModel; 
    
    namespace PerformanceLibrary
    {    
        public class Book    
        {        
            private Collection<string> _Pages;         
    
            public Book(string[] pages)        
            {            
                _Pages = new Collection<string>(pages);        
            }         
    
            public Collection<string> Pages        
            {            
                get { return _Pages; }        
            }    
        }
    }