Bagikan melalui


CA1024: Gunakan properti jika sesuai

Properti Nilai
ID Aturan CA1024
Judul Gunakan properti jika sesuai
Golongan Desain
Perbaikan bersifat disruptif atau non-disruptif Merusak
Diaktifkan secara default di .NET 9 No

Penyebab

Metode memiliki nama yang dimulai dengan Get, tidak mengambil parameter, dan mengembalikan nilai yang bukan array.

Secara default, aturan ini hanya melihat metode yang terlihat secara eksternal, tetapi ini dapat dikonfigurasi.

Deskripsi aturan

Dalam kebanyakan kasus, properti mewakili data dan metode melakukan tindakan. Properti diakses seperti bidang, yang membuatnya lebih mudah digunakan. Metode adalah kandidat yang baik untuk menjadi properti jika salah satu kondisi ini ada:

  • Metode ini tidak mengambil argumen dan mengembalikan informasi status objek.
  • Metode menerima argumen tunggal untuk mengatur beberapa bagian dari status objek.

Cara memperbaiki pelanggaran

Untuk memperbaiki pelanggaran aturan ini, ubah metode menjadi properti.

Kapan harus menekan peringatan

Tekan peringatan dari aturan ini jika metode memenuhi salah satu kriteria berikut. Dalam situasi ini, metode lebih disukai daripada properti.

  • Metode ini tidak dapat berulah sebagai bidang.
  • Metode ini melakukan operasi yang memakan waktu. Metode ini jauh lebih lambat daripada waktu yang diperlukan untuk mengatur atau mendapatkan nilai bidang.
  • Metode melakukan konversi. Mengakses bidang tidak mengembalikan versi data yang dikonversi yang disimpannya.
  • Metode ini Get memiliki efek samping yang dapat diamati. Mengambil nilai bidang tidak menghasilkan efek samping apa pun.
  • Urutan eksekusi penting. Mengatur nilai bidang tidak bergantung pada kemunculan operasi lain.
  • Memanggil metode dua kali berturut-turut menciptakan hasil yang berbeda.
  • Metode ini static tetapi mengembalikan objek yang dapat diubah oleh pemanggil. Mengambil nilai bidang tidak memungkinkan pemanggil untuk mengubah data yang disimpan oleh bidang .
  • Metode mengembalikan array.

Menyembunyikan peringatan

Jika Anda hanya ingin menyembunyikan satu pelanggaran, tambahkan arahan praprosedur ke file sumber Anda untuk dinonaktifkan lalu aktifkan kembali aturannya.

#pragma warning disable CA1024
// The code that's violating the rule is on this line.
#pragma warning restore CA1024

Untuk menonaktifkan aturan untuk file, folder, atau proyek, atur tingkat keparahannya ke none dalam file konfigurasi.

[*.{cs,vb}]
dotnet_diagnostic.CA1024.severity = none

Untuk informasi selengkapnya, lihat Cara menyembunyikan peringatan analisis kode.

Mengonfigurasi kode yang akan dianalisis

Gunakan opsi berikut untuk mengonfigurasi bagian mana dari codebase Anda yang akan menjalankan aturan ini.

Anda dapat mengonfigurasi opsi ini hanya untuk aturan ini, untuk semua aturan yang berlaku untuknya, atau untuk semua aturan dalam kategori ini (Desain) yang berlaku untuk aturan ini. Untuk informasi selengkapnya, lihat Opsi konfigurasi aturan kualitas kode.

Menyertakan permukaan API tertentu

Anda dapat mengonfigurasi bagian basis kode mana yang akan dijalankan aturan ini, berdasarkan aksesibilitasnya, dengan mengatur opsi api_surface. Misalnya, untuk menentukan bahwa aturan hanya boleh dijalankan pada permukaan API non-publik, tambahkan pasangan kunci-nilai berikut ke file .editorconfig di proyek Anda:

dotnet_code_quality.CAXXXX.api_surface = private, internal

Nota

Ganti bagian XXXXCAXXXX dengan ID aturan yang berlaku.

Contoh

Contoh berikut berisi beberapa metode yang harus dikonversi ke properti dan beberapa yang seharusnya tidak karena tidak berulah seperti bidang.

public class Appointment
{
    static long nextAppointmentID;
    static double[] discountScale = { 5.0, 10.0, 33.0 };
    string? customerName;
    long customerID;
    DateTime when;

    // Static constructor.
    static Appointment()
    {
        // Initializes the static variable for Next appointment ID.
    }

    // This method violates the rule, but should not be a property.
    // This method has an observable side effect. 
    // Calling the method twice in succession creates different results.
    public static long GetNextAvailableID()
    {
        nextAppointmentID++;
        return nextAppointmentID - 1;
    }

    // This method violates the rule, but should not be a property.
    // This method performs a time-consuming operation. 
    // This method returns an array.
    public Appointment[] GetCustomerHistory()
    {
        // Connect to a database to get the customer's appointment history.
        return LoadHistoryFromDB(customerID);
    }

    // This method violates the rule, but should not be a property.
    // This method is static but returns a mutable object.
    public static double[] GetDiscountScaleForUpdate()
    {
        return discountScale;
    }

    // This method violates the rule, but should not be a property.
    // This method performs a conversion.
    public string GetWeekDayString()
    {
        return DateTimeFormatInfo.CurrentInfo.GetDayName(when.DayOfWeek);
    }

    // These methods violate the rule and should be properties.
    // They each set or return a piece of the current object's state.

    public DayOfWeek GetWeekDay()
    {
        return when.DayOfWeek;
    }

    public void SetCustomerName(string customerName)
    {
        this.customerName = customerName;
    }

    public string? GetCustomerName()
    {
        return customerName;
    }

    public void SetCustomerID(long customerID)
    {
        this.customerID = customerID;
    }

    public long GetCustomerID()
    {
        return customerID;
    }

    public void SetScheduleTime(DateTime when)
    {
        this.when = when;
    }

    public DateTime GetScheduleTime()
    {
        return when;
    }

    // Time-consuming method that is called by GetCustomerHistory.
    Appointment[] LoadHistoryFromDB(long customerID)
    {
        ArrayList records = new ArrayList();
        // Load from database.
        return (Appointment[])records.ToArray();
    }
}
Public Class Appointment
    Shared nextAppointmentID As Long
    Shared discountScale As Double() = {5.0, 10.0, 33.0}
    Private customerName As String
    Private customerID As Long
    Private [when] As Date

    ' Static constructor.
    Shared Sub New()
        ' Initializes the static variable for Next appointment ID.
    End Sub

    ' This method violates the rule, but should not be a property.
    ' This method has an observable side effect. 
    ' Calling the method twice in succession creates different results.
    Public Shared Function GetNextAvailableID() As Long
        nextAppointmentID += 1
        Return nextAppointmentID - 1
    End Function

    ' This method violates the rule, but should not be a property.
    ' This method performs a time-consuming operation. 
    ' This method returns an array.
    Public Function GetCustomerHistory() As Appointment()
        ' Connect to a database to get the customer's appointment history.
        Return LoadHistoryFromDB(customerID)
    End Function

    ' This method violates the rule, but should not be a property.
    ' This method is static but returns a mutable object.
    Public Shared Function GetDiscountScaleForUpdate() As Double()
        Return discountScale
    End Function

    ' This method violates the rule, but should not be a property.
    ' This method performs a conversion.
    Public Function GetWeekDayString() As String
        Return DateTimeFormatInfo.CurrentInfo.GetDayName([when].DayOfWeek)
    End Function

    ' These methods violate the rule and should be properties.
    ' They each set or return a piece of the current object's state.

    Public Function GetWeekDay() As DayOfWeek
        Return [when].DayOfWeek
    End Function

    Public Sub SetCustomerName(customerName As String)
        Me.customerName = customerName
    End Sub

    Public Function GetCustomerName() As String
        Return customerName
    End Function

    Public Sub SetCustomerID(customerID As Long)
        Me.customerID = customerID
    End Sub

    Public Function GetCustomerID() As Long
        Return customerID
    End Function

    Public Sub SetScheduleTime([when] As Date)
        Me.[when] = [when]
    End Sub

    Public Function GetScheduleTime() As Date
        Return [when]
    End Function

    ' Time-consuming method that is called by GetCustomerHistory.
    Private Function LoadHistoryFromDB(customerID As Long) As Appointment()
        Dim records As ArrayList = New ArrayList()
        Return CType(records.ToArray(), Appointment())
    End Function
End Class

Mengontrol ekspansi properti di debugger

Salah satu alasan programmer menghindari penggunaan properti adalah karena mereka tidak ingin debugger untuk mengotomatiskannya. Misalnya, properti mungkin melibatkan pengalokasian objek besar atau memanggil P/Invoke, tetapi mungkin tidak benar-benar memiliki efek samping yang dapat diamati.

Anda dapat mencegah debugger memperluas properti secara otomatis dengan menerapkan System.Diagnostics.DebuggerBrowsableAttribute. Contoh berikut menunjukkan atribut ini diterapkan ke properti instans.

Imports System.Diagnostics

Namespace Microsoft.Samples
    Public Class TestClass
        ' [...]

        <DebuggerBrowsable(DebuggerBrowsableState.Never)> _
        Public ReadOnly Property LargeObject() As LargeObject
            Get
                ' Allocate large object
                ' [...]
            End Get
        End Property
    End Class
End Namespace
using System.Diagnostics;

namespace Microsoft.Samples
{
    class TestClass
    {
        // [...]

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        public LargeObject LargeObject
        {
            get
            {
                // Allocate large object
                // [...]
            }
        }
    }
}