繁体   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