Class.Class vs Namespace.Class for top level general use class libraries?

后端 未结 7 1798
难免孤独
难免孤独 2020-12-11 07:52

Which one is more acceptable (best-practice)?:

namespace NP
   public static class IO
   public static class Xml
   ...
   // extension methods

using NP;

I         


        
7条回答
  •  孤城傲影
    2020-12-11 08:09

    The whole point of namespaces is that they are used to organise your code:

    Namespaces are heavily used within C# programs in two ways. Firstly, the .NET Framework classes use namespaces to organize its many classes. Secondly, declaring your own namespaces can help control the scope of class and method names in larger programming projects.

    When you look at the .NET framework itself, you can see that virtually everything is structured like your first example (namespaces), and virtually nothing is structured like your second example (nested types). The rare occasions that nested types are used are when they are so closely tied to the outer type that they are essentially part of it, but need to be a separate class for reasons such as code re-use.

    So if by "best practice" you mean "using things for the purpose they were designed", "most like the .NET framework" and "corresponding most closely to .NET design paradigms" then there is no contest; use namespaces for organisation, not nested types.

    Regarding your edit - no, there is no performance difference that will matter in the real world.

提交回复
热议问题