相关疑难解决方法(0)

在C#中,为什么String是一个行为类似值的引用类型?

String是一种引用类型,即使它具有值类型的大多数特性,例如是不可变的并且具有==重载以比较文本而不是确保它们引用相同的对象.

为什么字符串不是一个值类型呢?

c# string clr value-type reference-type

348
推荐指数
8
解决办法
16万
查看次数

未分配的局部变量和短路评估

我有两种方法,它们都正确编译:

public int A()
{
    int i;
    if(!int.TryParse("0", out i))
    {
        return -1;
    }
    // do sth
    return i;
}

public int B()
{
    int i;
    if(true)
    {
        return -1;
    }
    return i;
}
Run Code Online (Sandbox Code Playgroud)

在第二种情况(方法B)中,编译器足够聪明,可以检测到该变量i从未被使用过,所以它不会抱怨不分配它.

但是,我有另一个例子(两者的组合)似乎等同于方法B:

public int C()
{
    int i;
    if (true || !int.TryParse("0", out i))
    {
        return -1;
    }
    return i;
}
Run Code Online (Sandbox Code Playgroud)

VisualStudio 2012(.NET Framework 4.6.01055)下在Windows上进行编译时,会抛出错误:Use of unassigned local variable 'i'.解决方案是:

  • i用任何值初始化,或
  • 使用| …

c#

6
推荐指数
1
解决办法
118
查看次数

标签 统计

c# ×2

clr ×1

reference-type ×1

string ×1

value-type ×1