简体   繁体   中英

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". 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.

Note that everywhere else the alias is being used works fine, it's only inside these linq delegates that it breaks. 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:

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:

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.

Thanks for the hint nemesv - I should know better than to trust the design-time compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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