3

Case 1: we can convert type by the following ways .....

  1. First way

        int someInt = 10;
        double someDouble = (double) someInt;
    
  2. Same thing in second way

        int someInt = 10;
        double someDouble = Convert.ToDouble(someInt);
    

Case 2: We can convert somethings into string by the following ways .......

  1. First way

        int someInt = 10;
        string someString =  someInt.ToString();
    
  2. Second way

        int someInt = 10;
        string someString =  someInt.ToString(CultureInfo.InvariantCulture);
    

Now my question is which one is good?? I am asking this question because ReSharper always gives me suggestion like 2nd way for both cases. I don't which one should I follow.

4

2 回答 2

3
  1. 案例1 - 两种方式都相同,第一种方式更快一点。
  2. 案例 2 - 第一种方式可能很危险,因为int.ToString()用作Culture.CurrentCulture参数(因此结果可能因计算机而异):

如:

someInt.ToString() == someInt.ToString(CultureInfo.CurrentCulture);
于 2013-06-17T06:39:14.863 回答
0

强制转换变量只是调用显式运算符方法,这是句法技巧。通过方法进行强制转换和转换完全相同或应该完全相同。不同的是特定类如何选择实现它。您可以让转换运算符处理 null 或不处理 null,这取决于您。

考虑我制作的以下自定义类。想想看,铸造中发生的一切都可以在方法中以相同的方式完成。这只是格式化魔术。

//explicitly convert int to my class
public static explicit operator MyClass(int t)
{
return new MyClass();
}

//static method to convert int to my class
public static MyClass ToMyClass()
{
return new MyClass();
}
于 2013-06-17T06:39:41.033 回答