Dav*_*enn 92 c# extension-methods
可以将扩展方法应用于类吗?
例如,扩展DateTime以包含可以调用的Tomorrow()方法,如:
DateTime.Tomorrow();
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用
static DateTime Tomorrow(this Datetime value) { //... }
Run Code Online (Sandbox Code Playgroud)
要么
public static MyClass {
public static Tomorrow() { //... }
}
Run Code Online (Sandbox Code Playgroud)
对于类似的结果,但我如何扩展DateTime以便我可以调用DateTime.Tomorrow?
Kum*_*umu 177
使用扩展方法.
例如:
namespace ExtensionMethods
{
public static class MyExtensionMethods
{
public static DateTime Tomorrow(this DateTime date)
{
return date.AddDays(1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
DateTime.Now.Tomorrow();
Run Code Online (Sandbox Code Playgroud)
要么
AnyObjectOfTypeDateTime.Tomorrow();
Run Code Online (Sandbox Code Playgroud)
And*_*are 68
除非现有类型标记为partial,否则无法将方法添加到现有类型,只能通过扩展方法添加看似现有类型成员的方法.由于这种情况,您无法向类型本身添加静态方法,因为扩展方法使用该类型的实例.
没有什么可以阻止你创建自己的静态助手方法,如下所示:
static class DateTimeHelper
{
public static DateTime Tomorrow
{
get { return DateTime.Now.AddDays(1); }
}
}
Run Code Online (Sandbox Code Playgroud)
你会用这个:
DateTime tomorrow = DateTimeHelper.Tomorrow;
Run Code Online (Sandbox Code Playgroud)
Shu*_*oUk 18
扩展方法是用于创建静态方法的语法糖,其第一个参数是类型T的实例,看起来好像它们是T上的实例方法.
因此,在制作"静态扩展方法"时,很大程度上会失去这些好处,因为它们会使代码的读者感到困惑,甚至超过扩展方法(因为它们似乎是完全限定的,但实际上并未在该类中定义)没有语法上的好处(例如能够在Linq中以流畅的方式链接调用).
因为无论如何你都必须将扩展带入范围,我认为创建它更简单,更安全:
public static class DateTimeUtils
{
public static DateTime Tomorrow { get { ... } }
}
Run Code Online (Sandbox Code Playgroud)
然后通过以下方式在代码中使用它:
WriteLine("{0}", DateTimeUtils.Tomorrow)
Run Code Online (Sandbox Code Playgroud)
我能得到答案的最接近的方法是在System.Type
对象中添加扩展方法.不漂亮,但仍然很有趣.
public static class Foo
{
public static void Bar()
{
var now = DateTime.Now;
var tomorrow = typeof(DateTime).Tomorrow();
}
public static DateTime Tomorrow(this System.Type type)
{
if (type == typeof(DateTime)) {
return DateTime.Now.AddDays(1);
} else {
throw new InvalidOperationException();
}
}
}
Run Code Online (Sandbox Code Playgroud)
否则,IMO Andrew和ShuggyCoUk有更好的实施.