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

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

问题描述

在下面的代码简化,

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天全站免登陆