开发者

Can you have an extension method on a type instead of on an instance of a type?

开发者 https://www.devze.com 2022-12-28 02:22 出处:网络
I can have an extension method like this: DateTime d = new DateTime(); d 开发者_StackOverflow社区= d.GetRandomDate();

I can have an extension method like this:

DateTime d = new DateTime();
d 开发者_StackOverflow社区= d.GetRandomDate();

GetRandomDate is my extension method. However the above doesn't make much sense. What would be better is:

DateTime d = DateTime.GetRandomDate();

However, I don't know how to do this. An extension method created as:

public static DateTime GetRandomDate(this System.DateTime dt)

will only add the GetRandomDate() in the first example above, not the second one. Is there a way to achieve the desired behaviour?


Nope - not possible

You'll need to access the method on your own static class...


Why would you want to? If you want to call a static method, why not call it directly?

OK, you will need to use something like DateTimeHelper.GetRandomDate() instead of DateTime.GetRandomDate().


Just throwing this out there, but could you create a partial static class of datetime and throw the extension method on that?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号