簡體   English   中英

回歸會員的好壞做法

[英]Good or Bad Practice for Return Members

我不確定這是否是無效的做法; 或好的做法。 我不知所措的原因是我應該利用屬性而不是局部變量嗎?

我的推理和目標; 是對本地磁盤驅動器的非常基本的檢測。

我想指出一些事情:

  • 我沒有選擇boolean value因為我希望能夠調用此類返回驅動器路徑。 這樣從方法中檢索到的名稱; 可以在某些派生類中進行Path Combined

我的例子:

    public class Drive
    {
        // Variable:
        public string nameOfDrive;

        public Drive()
        {
            // Call Method.
            DriveName();
        }

        public string DriveName()
        {
            DriveInfo [] drives = DriveInfo.GetDrives();
            foreach (DriveInfo d in drives)
            {
                // Verify Valid 'C:' is Present.
                if (d.Name == @"C:")
                {
                    // Set Name:
                    nameOfDrive = d.Name;
                    // Return Result.
                    return d.Name;
                }
            }
            // Exception:
            throw new Exception("Unable to locate the C: Drive... Please map the correct drive.");
        }

    }
    /*
     * The above method and class contains a verification
     * for the 'C:' Drive.  Once the items are validated;
     * it will create a return variable for the 'C:'.  
     * Otherwise it will throw an Exception.
    */

現在,我不確定什么是更好的做法。 我應該使用屬性而不是public string nameOfDrive 還是我真的距離太遠了-這不是返回可在其他類中使用的值的最佳方法嗎? 還是直接引用成員變量是一種不好的做法?

第二個例子:

    public class Drive
    {
        private string nameOfDrive;
        public string NameOfDrive
        {
            get { return nameOfDrive; }
        }
        public Drive()
        {
            // Call Method.
            DriveName();
        }
        public string DriveName()
        {
            // Obtain Drive Information:
            DriveInfo [] drives = DriveInfo.GetDrives();
            foreach (DriveInfo d in drives)
            {
                // Verify Valid 'C:' is Present.
                if (d.Name == @"C:")
                {
                    // Set Name:
                    nameOfDrive = d.Name;
                    // Return Result.
                    return d.Name;
                }
            }
            // Exception:
            throw new Exception("Unable to locate the C: Drive... Please map the correct drive.");
        }
    }
    /*
     * The above method and class contains a verification
     * for the 'C:' Drive.  Once the items are validated;
     * it will create a return variable for the 'C:'.  
     * Otherwise it will throw an Exception.
    */

這樣,它將其標記為只讀,並確保它從方法中讀取正確的值?


更新:

我感謝您的回答; 但是為什么有更好的做法呢?

  • 它對安全性有益嗎?
  • 只是整潔?
  • 更靈活

是什么使它成為更好的解決方案; 這就是我試圖理解的。

您可以使用Lazy類執行此操作。 它是專門為解決延遲初始化值而需要花費一些時間來計算的確切問題而設計的。 您可以為Lazy對象提供一個用於計算值的方法,第一次請求該值時,它將使用該函數生成該值,並且所有后續調用僅返回該第一個值。 它還具有線程安全的優點(該函數將僅被調用一次,無論有多少人在生成該值之前請求該值,並且他們都等到計算得出該值為止)。

public class Drive
{
    private Lazy<string> nameOfDrive = new Lazy<string>(DriveName);

    public string NameOfDrive
    {
        get { return nameOfDrive.Value; }
    }

    private static string DriveName()
    {
        DriveInfo[] drives = DriveInfo.GetDrives();

        foreach (DriveInfo d in drives)
        {
            if (d.Name == @"C:")
                return d.Name;
        }

        throw new Exception("Unable to locate the C: Drive... Please map the correct drive.");
    }
}

我將使用帶有私有成員變量的只讀屬性。 這樣,如果您在不破壞調用代碼的情況下更改了查找驅動器號的方式,就更容易更新類。

為什么您的DriveName方法返回任何內容? 它是公開使用還是僅用於填充NameOfDrive屬性? 如果僅在類中使用它,則將其設為私有且無效。

編輯:考慮一下,這似乎不僅是檢查驅動器是否存在,而且還要檢查字母開頭的一種奇怪方法。 為什么要求用戶的驅動器號為C: 用戶設置機器的方式無關緊要。 他們應該能夠將自己的操作系統驅動器設為Q:如果他們願意,那么它就不會破壞您的代碼。

盡管這不一定是壞習慣,但這也不是好習慣。

在大多數情況下,當您有一個簡單的數據類(通常不涉及任何實際代碼,只是一種存儲一些值的方法)時,應使用字段。 如果您超出了該級別的復雜性,通常應該具有類使用屬性。 原因如下:

  1. 稍后從字段轉換為屬性將破壞依賴關系,並要求重新編譯使用您的類的所有代碼
  2. 屬性具有更細粒度的控制。 快速瀏覽一下您的用例,看起來您應該擁有一個自動填充並緩存驅動器號的getter,並將默認的setter設為私有,因此它是只讀的
  3. 屬性可以是虛擬的。 這意味着人們將您的課程擴展到您最初想象的范圍之外要容易得多。

我將創建一個類(甚至擴展)來提取cdrive。 讓消費者根據自己的需求拋出錯誤。

通過創建通用方法,該方法允許根據情況重用該過程,並堅持使用將概念隔離為唯一對象的面向對象原理。

void Main()
{

  if (Drive.AcquireCDrive() == null)
      throw new Exception("Unable to locate the C: Drive... Please map the correct drive.");

}

public class Drive
{
    public static DriveInfo AcquireCDrive()
    {
       return DriveInfo.GetDrives()
                       .OfType<DriveInfo>()
                       .Where (drive => drive.IsReady)
                       .FirstOrDefault( drive => drive.Name.Contains(@"C:"));
    }
} 

更好的做法可能是使用只讀屬性,但要延遲加載它。

請注意以下內容,我將DriveName()方法DriveName()私有,並且沒有在構造函數中調用DriveName()方法。

public class Drive
{
    private string nameOfDrive = null;

    public string NameOfDrive
    {
        get 
        {
            if (nameOfDrive == null)
                nameOfDrive = DriveName();
            return nameOfDrive; 
        }
    }

    public Drive()
    {    }

    private string DriveName()
    {
        DriveInfo[] drives = DriveInfo.GetDrives();

        foreach (DriveInfo d in drives)
        {
            if (d.Name == @"C:")            
                return d.Name;
        }

        throw new Exception("Unable to locate the C: Drive... Please map the correct drive.");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM