zoukankan      html  css  js  c++  java
  • 谈static在C ++ 和C#中的不同处理

    来源:基于.NET的企业开发 - 博客园

    先看这段C#代码
    public class C {
    public static void M() {
    Console.WriteLine("call in class C");
    }
    }

    public class D : C {
    public new static void M() {
    Console.WriteLine("call in class D");
    }
    }

    public class E where T : C {
    public static void N() {
    T.M();
    }
    }
      代码是错误的,不允许一个instance来call一个static method。如果你编译的话,会提示:
    Error 2 'T' is a 'type parameter', which is not valid in the given context

      为什么?
      从语言设计的角度来看,针对上面的代码,下面的三种情况只能有一种为true。
      1. 本身就是错误的写法
      2. E.N() calls C.M() no matter what T is.
    3. E.N() calls C.M() but E.N() calls D.M().

      如果按照2设计,会有用户期望当T是class D的时候,执行class D的method M,而不是C。Static之所以是static,因为它在编译时刻就可以被确切的determined,或者说,在静态代码分析阶段,这个方法就可以被确定了。所以,如果按照3的方式来设计,我们就违背了这个原则。
    这样,只有1了。

    另外的解释:
    1. virtual static,为什么没这个东西?
    2. 没有this指针而已
    (以上内容转自同事的一个blog,做了简单的修改)

    不过,不清楚C++里面为什么允许这么做?
    public class Test{
    public static void Say(){}
    }

    Test t;
    Test* t2 = new Test();

    t.Say();
    t2->Say();
  • 相关阅读:
    Java 环境搭建的一些问题
    DefaultHttpClient is deprecated 【Api 弃用]】
    Java良葛格 学习笔记《二》
    Java良葛格 学习笔记
    JAVA EE 运行环境配置(包含JAVA SE)
    AIR使用文件对象操作文件和目录
    As3.0 类的【枚举】
    Java&&As3.0 中的final 关键字
    字符串参数组合
    PHP 超级全局变量
  • 原文地址:https://www.cnblogs.com/godwar/p/943473.html
Copyright © 2011-2022 走看看