Dav*_*ave 15 c# extension-methods
我正在阅读有关扩展方法的内容,并与他们进行一起讨论,看看它们是如何工作的,我试过这个:
namespace clunk {
public static class oog {
public static int doubleMe(this int x) {
return 2 * x;
}
}
class Program {
static void Main() {
Console.WriteLine(5.doubleMe());
}
}
}
Run Code Online (Sandbox Code Playgroud)
并按预期工作,使用doubleMe方法成功扩展int,打印10.
接下来,作为一个老C家伙,我想知道我是否可以这样做:
namespace clunk {
public static class BoolLikeC {
public static bool operator true(this int i) { return i != 0; }
public static bool operator false(this int i) { return i == 0; }
}
class Program {
static void Main() {
if ( 7 ) {
Console.WriteLine("7 is so true");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想如果前者可以工作,那么后者应该努力使得布尔上下文中使用的int将在int上调用扩展方法,检查7是否不等于0,并返回true.但相反,编译器甚至不喜欢后面的代码,并将红色波浪线放在这两个下面并说"Type expected".为什么不能这样做?
Eri*_*ert 18
非常聪明!一个不错的尝试,但遗憾的是我们没有实现"扩展一切",只是扩展方法.
我们考虑实现扩展属性,扩展操作符,扩展事件,扩展构造函数,扩展接口,你可以命名,但是大多数都没有引人注目,无法将它变成C#4或即将推出的C#版本.我们为你提到的那种东西设计了一种语法.我们在扩展属性方面做得更远; 我们几乎将扩展属性扩展到C#4但最终没有成功.悲伤的故事就在这里.
http://blogs.msdn.com/b/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx
所以,长话短说,没有这样的功能,但我们会考虑它的假设未来版本的语言.
如果你真的喜欢非零均值为真的复古C约定,你当然可以制作一个" ToBool()"扩展方法.int
正如其他人所说,C#中没有扩展运营商这样的东西.
你可以得到的最接近的,就是在自定义"桥"类型上使用隐式转换运算符:
// this works
BoolLikeC evil = 7;
if (evil) Console.WriteLine("7 is so true");
// and this works too
if ((BoolLikeC)7) Console.WriteLine("7 is so true");
// but this still won't work, thankfully
if (7) Console.WriteLine("7 is so true");
// and neither will this
if ((bool)7) Console.WriteLine("7 is so true");
// ...
public struct BoolLikeC
{
private readonly int _value;
public int Value { get { return _value; } }
public BoolLikeC(int value)
{
_value = value;
}
public static implicit operator bool(BoolLikeC x)
{
return (x.Value != 0);
}
public static implicit operator BoolLikeC(int x)
{
return new BoolLikeC(x);
}
}
Run Code Online (Sandbox Code Playgroud)