在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?

请每个回答只回答一个特征。


当前回答

命名空间解析顺序

为例。

namespace foo.bar.xyz{
  public class Foo{
    Exception e;   // you'll get compile time error here....
  }
}

因为

namespace foo.bar.Exception{
  class HowDoMyWayException : ApplicationException {
   // because someone did this
  } 
}

其他回答

下面是一个关于python的例子:

>>> print 07
7
>>> print 08
  File "<stdin>", line 1
    print 08
           ^
SyntaxError: invalid token

那不是很美吗?

尤其当你想到人类是如何写日期的时候,你会觉得很不周到,这有以下影响:

datetime.date(2010,02,07) # ok
datetime.date(2010,02,08) # error!

(原因是0x被解释为八进制,所以打印010打印8!)

Duff的C语言设备!

在C语言中,可以将do/while语句与switch语句交错使用。下面是memcpy使用此方法的示例:

void duff_memcpy( char* to, char* from, size_t count ) {
    size_t n = (count+7)/8;
    switch( count%8 ) {
    case 0: do{ *to++ = *from++;
    case 7:     *to++ = *from++;
    case 6:     *to++ = *from++;
    case 5:     *to++ = *from++;
    case 4:     *to++ = *from++;
    case 3:     *to++ = *from++;
    case 2:     *to++ = *from++;
    case 1:     *to++ = *from++;
            }while(--n>0);
    }
}

为什么c#的List<T>.AddRange()不让我添加T的子类型的元素?阀门列表< T > () ! 微软只需要多写一行代码:

public void AddRange<S>(
    IEnumerable<S> collection
) where S : T

在JavaScript中,你可以使用双位负(~~n)来代替Math.floor(n)(如果n是正数)或parseInt(n, 10)(即使n是负数)。N | N和N & N总是得到和~~ N相同的结果。

var n = Math.PI;
n; // 3.141592653589793
Math.floor(n); // 3
parseInt(n, 10); // 3
~~n; // 3
n|n; // 3
n&n; // 3

// ~~n works as a replacement for parseInt() with negative numbers…
~~(-n); // -3
(-n)|(-n); // -3
(-n)&(-n); // -3
parseInt(-n, 10); // -3
// …although it doesn’t replace Math.floor() for negative numbers
Math.floor(-n); // -4

单个位的求反(~)计算-(parseInt(n, 10) + 1),因此两个位的求反将返回-(-(parseInt(n, 10) + 1) + 1)。

更新:这里有一个jsPerf测试用例,比较了这些替代方案的性能。

在c++中,你可以做:

std::string my_str;
std::string my_str_concat = my_str + "foo";

但你不能:

std::string my_str_concat = "foo" + my_str;

操作符重载通常服从WTF。