CA1043:将整型或字符串参数用于索引器

类型名

UseIntegralOrStringArgumentForIndexers

CheckId

CA1043

类别

Microsoft.Design

是否重大更改

原因

公共或受保护类型包含使用 Int32Int64ObjectString 以外的索引类型的公共或受保护索引器。

规则说明

索引器(即索引属性),应将整型或字符串类型用于索引。这些类型一般用于为数据结构创建索引和提高库的可用性。Object 类型的使用应仅限于不能在设计时指定特定整型或字符串类型的那些情况。如果设计需要对索引使用其他类型,请重新考虑该类型是否代表逻辑数据存储区。如果该类型不代表逻辑数据存储区,请使用方法。

如何解决冲突

要修复与该规则的冲突,请将索引更改为整型或字符串类型,或者使用方法代替索引器。

何时禁止显示警告

仅在认真考虑非标准索引器的需要后,再禁止显示此规则发出的警告。

示例

下面的示例演示使用 Int32 索引的索引器。

Imports System

Namespace DesignLibrary

    Public Class Months

        Private month() As String = {"Jan", "Feb", "..."}

        Default ReadOnly Property Item(index As Integer) As String 
            Get 
                Return month(index)
            End Get 
        End Property 

    End Class 

End Namespace
using System;

namespace DesignLibrary
{
    public class Months
    {
        string[] month = new string[] {"Jan", "Feb", "..."};

        public string this[int index]
        {
            get
            {
                return month[index];
            }
        }
    }
}
using namespace System;

namespace DesignLibrary
{
    public ref class Months
    {
        array<String^>^ month;

    public:
        property String^ default[int]
        {
           String^ get(int index)
           {
              return month[index];
           }
           void set(int index, String^ value)
           {
              month[index] = value;
           }
        }

        Months()
        {
            month = gcnew array<String^>(12);
            month[0] = "Jan";
            month[1] = "Feb";
            //...;
        }
    };
}

相关规则

CA1023:索引器不应是多维的

CA1024:在适用处使用属性