假设我有一个object类型的变量o,需要转化成string类型的变量s。那么请问下列方式当中的那一个方案更加有效率:

1、

两种方式谁快谁慢?= (string) o;

2、
两种方式谁快谁慢?= o.ToString();

相关提示:
1、(string) 强制转换对应一句IL语句castclass,在IL中大概表现为:
      L_0019: ldloc.0
      L_001a: castclass string
      L_001f: stfld string WindowsApplication1.Form1::testString

这样的形势,注意强制转换只增加L_001a这一句IL语句。

2、o.ToString() 实际上是调用了从object继承出来的ToString()虚函数,这一个虚函数在string类型里面被重写,代码如下:
public override string ToString()
{
      return this;
}
如果效率有差别,差别是多大呢?答案在于实践当中。

相关文章:

  • 2022-12-23
  • 2022-01-20
  • 2021-06-10
  • 2021-11-05
  • 2022-12-23
  • 2021-12-17
  • 2021-07-11
  • 2021-07-07
猜你喜欢
  • 2021-06-02
  • 2021-09-28
  • 2021-07-12
  • 2021-09-11
  • 2021-04-08
  • 2022-12-23
相关资源
相似解决方案