开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜