再谈static在C++和C#中的不同处理
先看这段C#代码
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
Error 2 'T' is a 'type parameter', which is not valid in the given context
为什么?
从语言设计的角度来看,针对上面的代码,下面的三种情况只能有一种为true。
1. 本身就是错误的写法
2. E
3. E
如果按照2设计,会有用户期望当T是class D的时候,执行class D的method M,而不是C。Static之所以是static,因为它在编译时刻就可以被确切的determined,或者说,在静态代码分析阶段,这个方法就可以被确定了。所以,如果按照3的方式来设计,我们就违背了这个原则。
这样,只有1了。
另外的解释:
1. virtual static,为什么没这个东西?
2. 没有this指针而已
(以上内容转自同事的一个blog,做了简单的修改)
不过,不清楚C++里面为什么允许这么做?
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)