如何使用c#扩展方法扩展类? [英] How do I extend a class with c# extension methods?

查看:255
本文介绍了如何使用c#扩展方法扩展类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以将扩展方法应用于该类吗?

Can extension methods be applied to the class?

例如,扩展DateTime以包括一个Tomorrow()方法,该方法可以像这样调用:

For example, extend DateTime to include a Tomorrow() method that could be invoked like:

DateTime.Tomorrow();

我知道我可以使用

static DateTime Tomorrow(this Datetime value) { //... }

Or

public static MyClass {
  public static Tomorrow() { //... }
}

得到类似的结果,但是如何扩展DateTime以便调用DateTime.Tomorrow ?

for a similar result, but how can I extend DateTime so that I could invoke DateTime.Tomorrow?

推荐答案

除非将现有类型标记为部分,否则不能将方法添加到现有类型中,只能添加<通过扩展方法,em>出现成为现有类型的成员。由于是这种情况,您不能将静态方法添加到类型本身,因为扩展方法使用该类型的实例。

You cannot add methods to an existing type unless the existing type is marked as partial, you can only add methods that appear to be a member of the existing type through extension methods. Since this is the case you cannot add static methods to the type itself since extension methods use instances of that type.

没有什么可以阻止您创建自己的静态帮助器方法的像这样:

There is nothing stopping you from creating your own static helper method like this:

static class DateTimeHelper
{
    public static DateTime Tomorrow
    {
        get { return DateTime.Now.AddDays(1); }
    }
}

您将这样使用:

DateTime tomorrow = DateTimeHelper.Tomorrow;

这篇关于如何使用c#扩展方法扩展类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆