在条件范围内声明一个隐式类型变量并在外部使用它 [英] Declaring an implicitly typed variable inside conditional scope and using it outside

查看:37
本文介绍了在条件范围内声明一个隐式类型变量并在外部使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的简化代码中,

if(city == "New York City")
{
  var MyObject = from x in MyEFTable
                     where x.CostOfLiving == "VERY HIGH"
                     select x.*;

}
else
{
  var MyObject = from x in MyEFTable
                     where x.CostOfLiving == "MODERATE"
                     select x.*;

}

  foreach (var item in MyObject)
  {
     Console.WriteLine("<item's details>");
  }

在条件块之外无法访问变量 MyObject.如何在 if..else 之外进行迭代?

The variable MyObject is not accessible outside conditional block. How can I iterate outside the if..else ?

推荐答案

让我们澄清一下你的困惑问题.问题是您有两个局部变量,每个变量都具有相同的不可描述"类型——一系列匿名类型.

Let's clarify your confusing question. The problem is that you have two local variables, each of which has the same "unspeakable" type -- a sequence of anonymous type.

我会像这样更改您的特定代码:

I would change your specific code like this:

string cost = city == "NYC" ? "HIGH" : "MODERATE";
var query = from row in table 
            where row.Cost == cost 
            select new { row.Population, row.Elevation };

但是,如果由于某种原因您仍然需要保持代码结构不变,您可以这样做:

However, if you still need to maintain the structure of the code as it is for some reason, you can do it like this:

static IEnumerable<T> SequenceByExample<T>(T t){ return null; }
...
var query = SequenceByExample(new { Population = 0, Elevation = 0.0 } );
if (whatever)
    query = ...
else
    query = ...

这是一种称为通过示例强制转换"的技巧的变体,在该技巧中,您将匿名类型的示例提供给泛型方法.方法类型推断然后确定返回类型是什么,并将其用作隐式类型本地的类型.在运行时,它只会创建一个无用的对象,然后很快就会被丢弃.

This is a variation on a trick called "cast by example" where you give an example of an anonymous type to a generic method. Method type inference then figures out what the return type is, and uses that as the type of the implicitly typed local. At runtime, it does nothing but create a useless object that then gets discarded quickly.

这篇关于在条件范围内声明一个隐式类型变量并在外部使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆