如何预定义将包含匿名类型的变量? [英] How can you pre-define a variable that will contain an anonymous type?

查看:164
本文介绍了如何预定义将包含匿名类型的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的简化示例中,我想在result定义之前对其进行定义.下面的linq查询返回匿名类型列表. result将作为IEnumerable 来自linq查询,但是我不能在方法顶部以这种方式定义它.我正在尝试做的事情(在.NET 4中)吗?

In the simplified example below I want to define result before it is assinged. The linq queries below return lists of anonymous types. result will come out of the linq queries as an IEnumerable<'a> but I can't define it that way at the top of the method. Is what I am trying to do possible (in .NET 4)?

            bool large = true;
            var result = new IEnumerable();   //This is wrong

            List<int> numbers = new int[]{1,2,3,4,5,6,7,8,9,10}.ToList<int>();

            if (large)
            {
                result = from n in numbers
                             where n > 5
                             select new
                             {
                                 value = n
                             };
            }
            else
            {
                result = from n in numbers
                             where n < 5
                             select new
                             {
                                 value = n
                             };
            }

            foreach (var num in result)
            {
                Console.WriteLine(num.value);
            }

为清楚起见,我知道我在上面的示例中不需要匿名类型.只是通过一个简单的小例子来说明我的问题.

To be clear I know that I do not need anonymous types in the example above. It is just to illustrate my question with a small, simple example.

推荐答案

只能使用var声明匿名类型.好消息是,具有相同属性的匿名类型将是相同类型.如果您确实需要它(在此示例中您不需要它),则可以编写:

Anonymous types can be declared only with var. The good thing is that anonymous types with same properties will be the same types. If you really need it (in this sample you don't need it) then you can write:

var result = Enumerable.Repeat(new {value = 0}, 0); // stub value which will give needed type
if (...)
{
    result = ...;
}
else
{
    result = ...;
}

P.S .:即使在以前的.Net版本(低于4.0)中,这也是可能的

P.S.: this was possible even in previous .Net version (lower than 4.0)

这篇关于如何预定义将包含匿名类型的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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