简体   繁体   English

C#将变量声明为if语句

[英]C# declare variable into if statement

i want to do something like this using C# : 我想用C#做这样的事情:

if (i == 0)
{
 button a = new button();
}
else
{
 TextBlock a = new TextBlock();
}
mainpage.children.add(a);

But i get an error that 但我得到一个错误

Error 1 The name 'a' does not exist in the current context 错误1当前上下文中不存在名称“a”

Any ideas ? 有任何想法吗 ?

thank you in advance ! 先感谢您 !

You need a common base class that both button and Textblock derive from, and it needs to be declared outside of the if statement if it's to be accessed after the if is complete. 您需要一个buttonTextblock派生的公共基类,如果要在if完成后访问它,则需要在if语句之外声明它。 Control maybe? Control可能吗?

Control a;
if (i == 0)
{
 a = new button();
}
else
{
 a = new TextBlock();
}
mainpage.children.add(a);

Not knowing what specific control toolkit you're using (WPF maybe?) I can't advise further. 不知道你正在使用什么特定的控制工具包(WPF可能?)我无法进一步建议。 But I'd look at the signature for Add to get a clue - what's the parameter declared as? 但我会看看Add的签名以获得线索 - 声明的参数是什么?

Try declaring a outside of the scope of the if/else. 尝试宣告a的if / else语句的范围之外。 Like this: 像这样:

Control a;
if (i == 0)
{
  a = new button();
}
else
{
  a = new TextBlock();
}
mainpage.children.add(a);

You need to declare your variable in parent scope and give it a common base class. 您需要在父作用域中声明您的变量并为其提供一个公共基类。 The common base class for System.Windows.Controls.TextBlock and System.Windows.Controls.Button can be for example System.Windows.UIElement or System.Windows.FrameworkElement . System.Windows.Controls.TextBlockSystem.Windows.Controls.Button的公共基类可以是例如System.Windows.UIElementSystem.Windows.FrameworkElement So your code can look like this: 所以你的代码看起来像这样:

UIElement a;
if (i == 0)
{
    a = new Button();
}
else
{
    a = new TextBlock();
}
mainpage.children.add(a);

I found a discussion about declaring and assigning variables inside a condition here: http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/11a423f9-9fa5-4cd3-8a77-4fda530fbc67 我在这里找到了关于声明和分配变量的讨论: http//social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/11a423f9-9fa5-4cd3-8a77-4fda530fbc67

It seems it cannot be done in C#, even though you can in other languages 它似乎无法用C#完成,即使你可以使用其他语言

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

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