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

Ger*_*hes 1 .net c# 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
    }
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*iec 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
}
Run Code Online (Sandbox Code Playgroud)