zoukankan      html  css  js  c++  java
  • c#进阶 methods中2overload methods

     CLR并不知道发生了操作符重载这回事,因为在编译的过程中

    各种操作符都被生产了对应的代码。比如说+被生产为一个加法函数

    public sealed class Complex {
    public static Complex operator+(Complex c1, Complex c2) {
    //TO DO
    }
    }

    自己动手为 类A重载一个操作符

    public   class ClassA {
        
    public static int operator +(ClassA c1, int c2) {
            
    return ++c2;
            
    //TO DO
        }
    }
    static void Main(string[] args) {
            
    int a = 0;
            
    int b = 0;
            
    int c = 0;
            c 
    = a + b;
            ClassA ca 
    = new ClassA();
            Console.WriteLine(ca 
    + 1);
            Console.Read();
        }

    image

     

    image

    能够允许重载的操作符非常有限,只是一般的+ - 等等。

    CLR中更多的重载的可以参看

    ECMA specifications
    (www.ecma-international.org/publications/standards/Ecma-335.htm)

    书中说到其实他调用了

    op_Addition method,

    但使用 reflactor和IL DASM都看不到那个方法。。。

    查看的结果

    private static void Main(string[] args)
    {
        int a;
        int b;
        int c;
        a = 0;
        b = 0;
        c = 0;
        c = a + b;
        return;
    }
     
    
    
    .method private hidebysig static void  Main(string[] args) cil managed
    {
      
    .entrypoint
      
    // Code size       12 (0xc)
      .maxstack  2
      
    .locals init ([0int32 a,
               [
    1int32 b,
               [
    2int32 c)
      
    IL_0000:  nop
      
    IL_0001:  ldc.i4.0
      
    IL_0002:  stloc.0
      
    IL_0003:  ldc.i4.0
      
    IL_0004:  stloc.1
      
    IL_0005:  ldc.i4.0
      
    IL_0006:  stloc.2
      
    IL_0007:  ldloc.0
      
    IL_0008:  ldloc.1
      
    IL_0009:  add
      
    IL_000a:  stloc.2
      
    IL_000b:  ret
    // end of method Program::Main

    我的个人观点:

    操作符重载通常会造成歧义而不被推崇,除非是为了性能特殊地方使用。如某些基础数据类型中需要重写比较==和!=等等。

  • 相关阅读:
    关于Design Complier/Library Compiler的跌坑(坑爹)记录
    博客暂时停更
    简单的Verilog测试模板结构
    存储器的设计/建模
    静态时序分析的三种分析模式(简述)
    Linux系统的基本使用
    Modelsim的使用——复杂的仿真
    Python-第三方库requests
    MySQL查询结果写入到文件总结
    MySQL创建函数报“ERROR 1418 ”错误,不能创建函数
  • 原文地址:https://www.cnblogs.com/facingwaller/p/1916446.html
Copyright © 2011-2022 走看看