声明一个var而不初始化它......就在那里

时间:2015-02-25 11:07:08

标签: c# .net var

有没有办法或诀窍来做类似的事情:

var existingUsers; // This is not possible, but i need it to be global :)
try
{
    existingUsers = Repo.GetAll(); // This may crash, and needs to be in a try
}
catch (Exception)
{
    throw new Exception("some error, don't bother");
}

if (existingUsers.Count > 0)
    {
        //some code
    }

或者也许是我尝试做的替代方案?

9 个答案:

答案 0 :(得分:5)

这里的正确答案是放弃使用var并正确指定existingUsers块之外的try...catch类型:

List<User> existingUsers = null; // or whatever is the right type!
try
{
    existingUsers = Repo.GetAll(); // This may crash, and needs to be in a try
}
catch (Exception)
{
    throw new Exception("some error, don't bother");
}
if (existingUsers.Count > 0)
{
    //some code
}

答案 1 :(得分:3)

您必须在声明变量时指定类型 - 显式或推断。但你可以这样做,这是你想要的:

var existingUsers = (List<User>)null;
try
{
    existingUsers = Repo.GetAll();
}
catch (Exception)
{
    throw new Exception("some error, don't bother");
}
if (existingUsers.Count() > 0)
{
    //some code
}

答案 2 :(得分:1)

如果你需要它是全局的,因为你在try / catch之外使用它的一些方法/属性,你假设它有一些接口(例如ICollection):

ICollection existingUsers; 
try
{
    existingUsers = Repo.GetAll(); // This may crash, and needs to be in a try
}
catch (Exception)
{
    throw new Exception("some error, don't bother");
}  
if (existingUsers.Count > 0)
{
    //some code
}

答案 3 :(得分:1)

作为在外部范围内使用变量的替代方法,请考虑在try块内进行所有处理:

try
{
    var existingUsers = Repo.GetAll(); // This may crash, and needs to be in a try
    if (existingUsers.Count > 0)
    {
      // Some code
    }

    return existingUsers;
}
catch (Exception)
{
    throw new Exception("some error, don't bother");
}    

这非常有效,例如,如果要返回值(如我在修改示例中所示)。

我还建议捕获一个特定的异常(例如RepositoryOperationFailedException),以区分这种情况与“某些代码”失败的情况。

答案 4 :(得分:1)

你不能在C#中“声明var”。 var关键字没有做任何特别的事情。它只是一个告诉编译器的快捷方式“嘿,我应该在这里输入一个类型,但我会让你自己选择类型,因为我很懒/我不确定类型/它会对声明多余”。当你写

var i = 0;

与写作完全相同

int i = 0;

如果您将鼠标放在大多数IDE中的var上,智能感知会告诉您它只是ìnt的占位符。

现在考虑这一行

var myVariable;

什么是var应该在这里? stringobjectintMyClassIMyInterface?编译器无法知道,所以它不能允许它。您必须自己填写正确的类型。

现在你的代码应该是

List<User> existingUsers; // This is not possible, but i need it to be global :)
try
{
    existingUsers = Repo.GetAll(); // This may crash, and needs to be in a try
}
catch (Exception)
{
    throw new Exception("some error, don't bother");
}

if (existingUsers.Count > 0)
{
    //some code
}

这将达到您想要的效果。

答案 5 :(得分:1)

如前所述,如果您知道existingUsers所需的具体类型,则可以将existingUsers声明为该类型。

List<User> existingUsers;

在少数情况下,您可能需要Repo.GetAll()的类型而不将其写出来,例如,如果类型的名称是一个不可读的混乱,具有多级泛型类型参数。在这些情况下,您可以写

var existingUsers = true ? null : Repo.GetAll();

但请如果您绝对没有其他选择,请执行此操作,并添加说明您为何会这样做的评论。

答案 6 :(得分:1)

您可以改用 object,并在稍后使用/不使用强制转换进行分配。

            object var1;
            switch (v)
            {
                case 1:
                    var1 = "String";
                    break;
                case 2:
                    var1 = 2;
                    break;
                default:
                    break;
            }

答案 7 :(得分:0)

我意识到这个问题的答案已被接受,但我想在讨论中加入一些内容......

在编写try / catch逻辑时,我有时会发现将try / catch逻辑与使用逻辑分开会更清楚。

对于您的示例,我可能会编写一个处理try / catch逻辑的tryGetExistingUsers()方法:

private List<User> tryGetExistingUsers() // Cannot return null
{
    try
    {
        var existingUsers = Repo.GetAll(); 

        if (existingUsers == null)
            throw new InvalidOperationException("List of existing users is null.");

        return existingUsers;
    }

    catch (Exception exception)
    {
        throw new Exception("some error, don't bother", exception);
    }
}

然后我会这样称呼它:

var existingUsers = tryGetExistingUsers();

if (existingUsers.Count > 0)
{
    // Some code.
}

然后主逻辑不会受到try / catch逻辑的污染。当然,这并没有显示处理重新抛出异常的位置;但OP代码也没有。

答案 8 :(得分:-1)

这是dynamic的用途:只需在代码中将var替换为dynamic

但要注意你放弃了类型安全!

编辑:给出批准的答案和评论: 是的,我知道这是一种相当丑陋的方式,我承认我并不完全理解这个问题的真正要求。

相关问题