简体   繁体   中英

c# extension method to define method that behaves like a static class / type method, not an instance method

I have this static method in a class:

public class MyTimeZoneHelperClass {

        public static TimeZoneInfo EST = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

        public static DateTime Convert_UTC_to_EST(this DateTime utcDateTime)
        {
            return TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, EST);
        }

        public static DateTime NowEST()
        {
            return DateTime.UtcNow.Convert_UTC_to_EST();
        }
}

I just went to write an extension method like for the DateTime TYPE that I was going to name "EstNow" so I could use DateTime.EstNow like this code uses DateTime.UtcNow. If I had that, I wouldn't have to reference this static class above - MyTimeZoneHelperClass.NowEst - my code would be just a little cleaner, I wouldn't have to remember that class name / I would prefer one class here instead of two.

So extension methods don't work like that. They are static methods but then you need an instance of he class to call the method - duh!

Is this possible? Can I (preferably easily) get the compiler to recognize a new / custom static method on a type?

No, you can't write "static extension" members to extend the type instead of instances of the type. It's just not part of C#. It has been discussed , and it may happen in the future, although I don't believe it's in the expected feature list for C# 9.

There is an open issue on the c# github as we speak: https://github.com/dotnet/csharplang/issues/2505

Open means it's not implemented yet. To summarise from it:

  1. There is no workaround to this, nothing to try that would mitigate the missing functionality
  2. There seems to be no interest to implement this at this point

There is no one on the ldm who thinks this is worth championing right now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM