简体   繁体   English

在linq语句中使用类型别名会生成错误

[英]Using a type alias in a linq statement is generating an error

For some reason this statement is working fine: 由于某种原因,这个声明工作得很好:

vms.Where(vm => vm.MessageType == ValidationMessage.EnumValidationMessageType.Warning)

But if at the top of the class, I define an alias (to save space): 但是如果在类的顶部,我定义了一个别名(以节省空间):

using MsgType = ValidationMessage.EnumValidationMessageType;

Then the resulting line of code: 然后得到的代码行:

vms.Where(vm => vm.MessageType == MsgType.Warning)

Gives me an error: 给我一个错误:

在此输入图像描述 "Delegate ' System.Func<ValidationMessage, int, bool> ' does not take 1 arguments". “委托' System.Func<ValidationMessage, int, bool> '不带1个参数”。 What's odd about that is that isn't the Delegate I'm using. 奇怪的是,这不是我正在使用的代表。 I'm using the ' System.Func<ValidationMessage, bool> ' overload of .Where<>() - same as when I wasn't using the alias. 我正在使用.Where<>()的' System.Func<ValidationMessage, bool> '重载 - 与我不使用别名时相同。

Note that everywhere else the alias is being used works fine, it's only inside these linq delegates that it breaks. 请注意,别名正在使用的其他地方工作正常,只有在这些linq委托中它才会中断。 Why is this happening? 为什么会这样?

Upon trying to run my program, all those errors cleared away and a single error appeared complaining about my type alias declaration. 在尝试运行我的程序时,所有这些错误都被清除,并且出现了一个错误,抱怨我的类型别名声明。

The problem was that the ValidationMessage.EnumValidationMessageType type existed within a namespace, which had been declared further up: 问题是ValidationMessage.EnumValidationMessageType类型存在于名称空间中,该名称空间已被进一步声明:

using WPF.Utilities.ObjectModel;
using MsgType = ValidationMessage.EnumValidationMessageType;

Of course, C# can't figure out where the type comes from based on prior namespace inclusions, I had to spell it out fully: 当然,根据先前的命名空间包含,C#无法确定类型的来源,我必须完全拼写出来:

using WPF.Utilities.ObjectModel;
using MsgType = WPF.Utilities.ObjectModel.ValidationMessage.EnumValidationMessageType;

Once I did that, the other problem went away. 一旦我这样做,另一个问题就消失了。

I guess I was just so caught up and confounded by the weird errors coming out of the linq statement, combined by the fact that VS didn't show any errors where I was using the alias in the ternary operators above, that I didn't see the obvious error there. 我想我只是因为linq语句中出现的奇怪错误而陷入困境,再加上VS没有显示任何错误,我在上面的三元运算符中使用了别名,我没有看到那里明显的错误。

Thanks for the hint nemesv - I should know better than to trust the design-time compiler. 感谢提示nemesv - 我应该知道比信任设计时编译器更好。

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

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