簡體   English   中英

類,使用方法的最佳方法是什么?

[英]Class, What's the best way to use methods?

我是編程的新手,學習自我,昨天我正在開發一個使用C#處理文件的類,我對此表示懷疑。當您有檢查方法和創建方法時,使用這些方法的最佳方法是什么?

是的,我知道,我在這里還不清楚,所以這里有個例子。

Files.cs(類)

namespace Working_with_Files
{
  class Files
  {

    public bool CheckFile(string path)
    {
        if (File.Exists(path))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public bool CreateFile(string path)
    {
        if (CheckFile(path))
        {
            return false;
        }
        else
        {
            File.Create(path);
            return true;
        }
    }

  }
}

使用此類方法的最佳和最快方法是什么? 因為當我使用CreateFile方法時,我必須檢查是否已經有一個同名文件。

最好的方法是在此方法內引用另一種方法? 像這樣;

namespace Working_with_Files
{
  class Files
  {

    public bool CheckFile(string path)
    {
        if (File.Exists(path))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public bool CreateFile(string path)
    {
        if (CheckFile(path))
        {
            return false;
        }
        else
        {
            File.Create(path);
            return true;
        }
    }

  }
}

最好的方法是使用CreateFile方法中的本機File.Exists? 像這樣;

namespace Working_with_Files
{
  class Files
  {

    public bool CheckFile(string path)
    {
        if (File.Exists(path))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public bool CreateFile(string path)
    {
        if (File.Exists(path))
        {
            return false;
        }
        else
        {
            File.Create(path);
            return true;
        }
    }
  }
}

或者,最好和最快的方法是在使用CreateFile方法之前在主程序上使用CheckFile方法?

這是我的疑問,對不起,如果我不清楚。

我個人采用以下方式:

如果“檢查”代碼超過一行代碼,則將其移至其自己的方法。

您也可以:

return File.Exists(path);

在CheckFile方法中。

但是,關於性能/速度,請不要擔心。 根據需要編寫任意數量的方法,速度差異很小。

在我看來,代碼的可讀性比微小的性能更重要。

不要過早優化! 第一個是“更清晰”,這是一個主觀的問題。

並請重命名功能:如果一個功能稱為CheckFile,則應“檢查”文件,內容或其他內容。 不檢查文件是否存在->重命名為FileExists

如果您想要最快的方法,那么我認為您只能在第一種情況下使用CreateFile方法。 因為它使用了現成的框架File.Exists和File.Create方法。 就像大多數開發人員所做的那樣-如果框架或語言提供了現成的功能,則在不滿足要求的情況下使用它們,或者將最大程度存在的功能組合在一起。

希望對您有所幫助!

假設您的方法需要額外的功能,並且您沒有為百合花鍍金...

我想您是在問是否要在另一種方法中重復一種方法的功能,答案是否定的。

“使用CreateFile方法之前在主程序上使用CheckFile方法”使您可以擴展CheckFile方法,而不會在功能上與CreateFile有所不同,這是更好的封裝方式。 (或者,如果始終需要,則使CreateFile調用CheckFile)

無需創建Files類的實例,因此可以使所有方法都像已經建議的那樣靜態,或者使用我認為更為優雅的代碼模式:

namespace Working_with_Files
{
    public class Files
    {
        private static Files instance;
        public static Files Instance { get { return instance; } }

        static Files()
        {
            instance = new Files();
        }

        private Files()
        {
        }

        public bool CheckFile(string path)
        ......no change in rest of code.....
    }
}

並調用方法:

Files.Instance.CheckFile("myfilehere")

暫無
暫無

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

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