Declaring an implicitly typed variable inside conditional scope and using it outside(在条件范围内声明一个隐式类型变量并在外部使用它)
问题描述
在下面的简化代码中,
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.
这篇关于在条件范围内声明一个隐式类型变量并在外部使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在条件范围内声明一个隐式类型变量并在外部使用它


基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01