CA1023:不應該使用多維索引子
型別名稱 |
IndexersShouldNotBeMultidimensional |
CheckId |
CA1023 |
分類 |
Microsoft.Design |
中斷變更 |
中斷 |
原因
public 或 protected 型別包含使用一個以上之索引的公用或保護之索引子 (Indexer)。
規則描述
索引子 (也就是索引屬性) 應使用單一索引。 多維式索引子會大幅降低程式庫的可用性。 如果設計需要多個索引,請考慮該型別是否代表邏輯資料存放區。 如果不是,請使用方法。
如何修正違規
若要修正此規則的違規情形,請將設計變更為使用長整數 (Long Integer) 或字串索引,或是改用方法而非索引子。
隱藏警告的時機
只有在仔細考慮確實需要非標準索引子之後,才能隱藏此規則的警告。
範例
下列範例所顯示的型別 DayOfWeek03,它的多維式索引子會違反規則。 該索引子可視為轉換型別,因此公開為方法較為適當。 該型別會在 RedesignedDayOfWeek03 中重新設計以滿足規則。
Imports System
Namespace DesignLibrary
Public Class DayOfWeek03
Private dayOfWeek(,) As String = {{"Wed", "Thu", "..."}, _
{"Sat", "Sun", "..."}}
' ...
Default ReadOnly Property Item(month As Integer, day As Integer) As String
Get
Return dayOfWeek(month - 1, day - 1)
End Get
End Property
End Class
Public Class RedesignedDayOfWeek03
Private dayOfWeek() As String = _
{"Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon"}
Private daysInPreviousMonth() As Integer = _
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30}
Function GetDayOfWeek(month As Integer, day As Integer) As String
Return dayOfWeek((daysInPreviousMonth(month - 1) + day) Mod 7)
End Function
End Class
End Namespace
using System;
namespace DesignLibrary
{
public class DayOfWeek03
{
string[,] dayOfWeek = {{"Wed", "Thu", "..."},
{"Sat", "Sun", "..."}};
// ...
public string this[int month, int day]
{
get
{
return dayOfWeek[month - 1, day - 1];
}
}
}
public class RedesignedDayOfWeek03
{
string[] dayOfWeek =
{"Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon"};
int[] daysInPreviousMonth =
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
public string GetDayOfWeek(int month, int day)
{
return dayOfWeek[(daysInPreviousMonth[month - 1] + day) % 7];
}
}
}
using namespace System;
namespace DesignLibrary
{
public ref class DayOfWeek03
{
array<String^, 2>^ dayOfWeek;
public:
property String^ default[int, int]
{
String^ get(int month, int day)
{
return dayOfWeek[month - 1, day - 1];
}
}
DayOfWeek03()
{
dayOfWeek = gcnew array<String^, 2>(12, 7);
dayOfWeek[0,0] = "Wed";
dayOfWeek[0,1] = "Thu";
// ...
dayOfWeek[1,0] = "Sat";
dayOfWeek[1,1] = "Sun";
// ...
}
};
public ref class RedesignedDayOfWeek03
{
static array<String^>^ dayOfWeek =
{"Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon"};
static array<int>^ daysInPreviousMonth =
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
public:
String^ GetDayOfWeek(int month, int day)
{
return dayOfWeek[(daysInPreviousMonth[month - 1] + day) % 7];
}
};
}