简体   繁体   English

在try块C#中定义变量

[英]Define variable in try block C#

I don't want to have ultra-deep nested blocks, so in cases that variable initialisation could error I would prefer to do it like this:我不想有超深嵌套块,所以在变量初始化可能出错的情况下,我更愿意这样做:

try
{
    var foo = GetFoo();
}
catch (FooException)
{
   Console.Write(...);
   throw;
}

var bar = GetBar(foo);

Of course it doesn't compile, I'm not allowed to use foo outside of the try-block that initialises it.当然它不能编译,我不允许在初始化它的 try 块之外使用foo

Putting a full type specification right above the block also sucks imo:将完整的类型规范放在块上方也很糟糕:

FooType foo;
try
{
    foo = GetFoo();
}
catch (FooException)
{
   Console.Write(...);
   throw;
}

var bar = GetBar(foo);

Even in less extreme cases like just int foo = 0;即使在不太极端的情况下,比如int foo = 0; already feels dirty, especially with that confusing unused initial value.已经感觉很脏,尤其是那些令人困惑的未使用的初始值。 The catch block exits the program anyway.无论如何, catch块都会退出程序。

How can I try-initialise a variable and use it outside of that scope, with minimal repetition and minimal characters typed?如何尝试初始化一个变量并在该范围之外使用它,并尽量减少重复和输入最少的字符?


Why I think I dislike the lifted variable declaration solution:为什么我认为我不喜欢提升的变量声明解决方案:

I prefer to avoid typed variable declarations.我更喜欢避免类型化变量声明。 I dislike repetition.我不喜欢重复。 I dislike the disconnect between declaration of the variable and its initialisation.我不喜欢变量声明与其初始化之间的脱节。 I dislike setting unused initial values.我不喜欢设置未使用的初始值。 The last two points probably come from a subconscious association with violation of immutability;最后两点可能来自与违反不变性的潜意识关联; I tend to like as many variables as possible being conceptually readonly and having separate declaration and initialisation contradicts that pattern.我倾向于喜欢尽可能多的变量在概念上是readonly并且有单独的声明和初始化与这种模式相矛盾。

One way to do this would be putting the initialization logic into another method and wrap it with try / catch there, so then you can have:一种方法是将初始化逻辑放入另一个方法中,并在那里用try / catch包装它,这样你就可以有:

var foo = InitializeFoo();
var bar = GetBar(foo);

private Foo InitializeFoo() 
{
     try {
         // initalize and return foo
     }
     catch {
        throw;
     }
}

You can generalize this by passing a delegate to the Initialize method that specifies the initiaze logic and use it for anything else.您可以通过将delegate传递给指定Initialize逻辑的Initialize方法来概括这一点,并将其用于其他任何事情。

public T InitializeVariable<T>(Func<T> initializeAction)
{
     try {
         var x = initializeAction();
         return x;
     }
     catch {
        throw;
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM