Aracılığıyla paylaş


CA1024: Uygun yerlerde özellikler kullan

Özellik Değer
Kural Kimliği CA1024
Başlık Uygun yerlerde özellikleri kullanın
Kategori Tasarım
Hataya neden olan veya bozulmayan düzeltme Yeni
.NET 8'de varsayılan olarak etkin Hayır

Neden

yöntemi ile başlayan Getbir ada sahiptir, parametre almaz ve dizi olmayan bir değer döndürür.

Varsayılan olarak, bu kural yalnızca dışarıdan görünen yöntemlere bakar, ancak bu yapılandırılabilir.

Kural açıklaması

Çoğu durumda, özellikler verileri temsil eder ve yöntemler eylemleri gerçekleştirir. Özelliklere alanlar gibi erişilir ve bu da daha kolay kullanılmasını sağlar. Yöntem, bu koşullardan biri mevcutsa özellik olmak için iyi bir adaydır:

  • yöntemi bağımsız değişken almaz ve bir nesnenin durum bilgilerini döndürür.
  • yöntemi, bir nesnenin durumunun bir kısmını ayarlamak için tek bir bağımsız değişken kabul eder.

İhlalleri düzeltme

Bu kuralın ihlalini düzeltmek için yöntemini bir özellik olarak değiştirin.

Uyarıların ne zaman bastırılması gerekiyor?

Yöntem aşağıdaki ölçütlerden birini karşılıyorsa, bu kuraldan bir uyarıyı bastırın. Bu gibi durumlarda, bir yöntem bir özellik için tercih edilir.

  • yöntemi alan olarak davranamaz.
  • yöntemi zaman alan bir işlem gerçekleştirir. yöntemi, bir alanın değerini ayarlamak veya almak için gereken süreden çok daha yavaştır.
  • yöntemi bir dönüştürme gerçekleştirir. Bir alana erişmek, depolandığı verilerin dönüştürülmüş bir sürümünü döndürmez.
  • yönteminin Get gözlemlenebilir bir yan etkisi vardır. Bir alanın değerinin alınması herhangi bir yan etki oluşturmaz.
  • Yürütme sırası önemlidir. Bir alanın değerini ayarlamak, diğer işlemlerin oluşumuna dayanmaz.
  • Yöntemin ardı ardına iki kez çağrılması farklı sonuçlar oluşturur.
  • yöntemidir static ancak çağıran tarafından değiştirilebilen bir nesne döndürür. Bir alanın değerinin alınması, çağıranın alan tarafından depolanan verileri değiştirmesine izin vermez.
  • yöntemi bir dizi döndürür.

Uyarıyı gizleme

Yalnızca tek bir ihlali engellemek istiyorsanız, kuralı devre dışı bırakmak ve sonra yeniden etkinleştirmek için kaynak dosyanıza ön işlemci yönergeleri ekleyin.

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

Bir dosya, klasör veya projenin kuralını devre dışı bırakmak için, yapılandırma dosyasındaki önem derecesini noneolarak ayarlayın.

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

Daha fazla bilgi için bkz . Kod analizi uyarılarını gizleme.

Çözümlemek için kod yapılandırma

Bu kuralın kod tabanınızın hangi bölümlerinde çalıştırılacaklarını yapılandırmak için aşağıdaki seçeneği kullanın.

Bu seçeneği yalnızca bu kural, geçerli olduğu tüm kurallar veya bu kategorideki (Tasarım) tüm kurallar için yapılandırabilirsiniz. Daha fazla bilgi için bkz . Kod kalitesi kuralı yapılandırma seçenekleri.

Belirli API yüzeylerini ekleme

Bu kuralın üzerinde çalıştırılacak kod tabanınızın hangi bölümlerini erişilebilirliklerine göre yapılandırabilirsiniz. Örneğin, kuralın yalnızca genel olmayan API yüzeyinde çalıştırılması gerektiğini belirtmek için projenizdeki bir .editorconfig dosyasına aşağıdaki anahtar-değer çiftini ekleyin:

dotnet_code_quality.CAXXXX.api_surface = private, internal

Örnek

Aşağıdaki örnek, özelliklere dönüştürülmesi gereken birkaç yöntem ve alanlar gibi davranmadıkları için dönüştürülmemesi gereken birkaç yöntem içerir.

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

Hata ayıklayıcıda özellik genişletmeyi denetleme

Programcıların özellik kullanmaktan kaçınmalarının bir nedeni, hata ayıklayıcının özelliği otomatik olarak açıklamasını istememeleridir. Örneğin, özelliği büyük bir nesne ayırmayı veya P/Invoke çağırmayı içerebilir, ancak aslında gözlemlenebilir yan etkileri olmayabilir.

uygulayarak System.Diagnostics.DebuggerBrowsableAttributehata ayıklayıcının özellikleri otomatik olarak genişletmesini engelleyebilirsiniz. Aşağıdaki örnekte bir örnek özelliğine uygulanan bu öznitelik gösterilmektedir.

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
                // [...]
            }
        }
    }
}