How to “import” a static class in C#?

后端 未结 9 1365
挽巷
挽巷 2020-12-28 19:08

I have created a public static class utils.cs I want to use it in other classes without prefixing method with utils, what\'s the syntax to do this ?

相关标签:
9条回答
  • 2020-12-28 19:27

    I'm not sure what you're trying to accomplish by omitting the Utils prefix from the method calls. But if it's just to save space or make the code a little easier to read, you could alias the import to a shorter name:

    using U = Utils;
    
    0 讨论(0)
  • 2020-12-28 19:30

    With C# 6, you can now use static imports (see msdn) For example,

    using static Utils;
    
    0 讨论(0)
  • 2020-12-28 19:38

    I have never really cared for the "global method" concept. Additionally, it seems that it makes much more readable / maintainable code to not have classes called 'Util' that contain helper methods of any type. Instead something like MathLib which at least documents what kind of method is being operated on.

    In the case of a financial library I could kind of see it where you may not want to always have to do MathLib.Sum() or whatever. Maybe you could introduce operator overloading to your types so that you could perform calculations on them with more simplified syntax when manipulating business your business objects?

    I may be a little biased(grumpy) after reading VB6 code over the last few weeks where global methods are all over the place. That being said this is just my two cents :)

    0 讨论(0)
提交回复
热议问题