Ran*_*mer 11 .net extension-methods
为简单起见,我们假设我想为int类型编写扩展方法?和int:
public static class IntExtentions
{
public static int AddOne(this int? number)
{
var dummy = 0;
if (number != null)
dummy = (int)number;
return dummy.AddOne();
}
public static int AddOne(this int number)
{
return number + 1;
}
}
Run Code Online (Sandbox Code Playgroud)
这可以只用一种方法吗?
Ste*_*ock 17
不幸的是.你可以做int?(或者你正在使用哪种可空类型)方法很容易调用非可空方法,所以你不需要用2种方法复制任何逻辑 - 例如
public static class IntExtensions
{
public static int AddOne(this int? number)
{
return (number ?? 0).AddOne();
}
public static int AddOne(this int number)
{
return number + 1;
}
}
Run Code Online (Sandbox Code Playgroud)
你不能.这可以通过编译以下代码进行实验验证
public static class Example {
public static int Test(this int? source) {
return 42;
}
public void Main() {
int v1 = 42;
v1.Test(); // Does not compile
}
}
Run Code Online (Sandbox Code Playgroud)
如果要在两种类型上使用它,则需要为每种类型(可为空且不可为空)编写扩展方法.