简体   繁体   English

C#无法从Lambda表达式获取价值

[英]C# unable to get value from lambda expression

Our company has purchased an app written in .NET and I have got a privilege to support it. 我们公司购买了一个用.NET编写的应用程序,我有幸提供支持。 I have never worked with .NET therefore I need some guidance with how to use lambda. 我从未使用过.NET,因此我需要一些有关如何使用lambda的指导。

In my cshtml file I am trying to get a value and validate if it's NULL or not. 在我的cshtml文件中,我试图获取一个值并验证它是否为NULL

I have tried to do this like so 我试图这样做

var appointment = x => x.AppointmentDate;

I receive compiler error " Cannot assign lambda expression to implicitly-typed local variable ". 我收到编译器错误“ 无法将lambda表达式分配给隐式类型的局部变量 ”。 I googled the error and tried the following. 我用错误搜索了谷歌并尝试了以下方法。

Func<DateTime, DateTime> appointment = x => x.AppointmentDate;

However now compiler gives this error " 'System.DateTime' does not contain a definition for 'AppointmentDate' and no extension method 'AppointmentDate' accepting a first argument of type 'System.DateTime' could be found (are you missing a using directive or an assembly reference?) " 但是,现在编译器给出此错误“ 'System.DateTime'不包含'AppointmentDate'的定义,并且找不到扩展方法'AppointmentDate'接受类型为'System.DateTime'的第一个参数(您是否缺少using指令或组装参考?)

How can I get a value to validate from lambda? 我如何从lambda获取值进行验证?

I think you're confused by what Func<T, TResult> is meant to be. 我想您对Func<T, TResult>的含义感到困惑。 The first parameter ( T ) is the input to the delegate; 第一个参数( T )是委托的输入 TResult is the output. TResult是输出。 So you probably want: 因此,您可能想要:

Func<Appointment, DateTime> appointmentFunction = x => x.AppointmentDate;

... where Appointment is the type of the object you're working with. ...其中Appointment是您正在处理的对象的类型。

Of course, that won't check whether the value is null - and in fact if the AppointmentDate property is just DateTime then it can't be null, as DateTime is a non-nullable value type. 当然,这不会检查该值是否为null实际上,如果AppointmentDate属性只是DateTime则它不能为null,因为DateTime是不可为空的值类型。

Note that in many cases you don't need to assign a lambda expression to a local variable - if you're calling a generic method, you can often let type inference work out the types for you. 请注意,在许多情况下,您无需为局部变量分配lambda表达式-如果您要调用通用方法,则通常可以让类型推断为您确定类型。 For example, if you have a List<Appointment> you could use: 例如,如果您具有List<Appointment> ,则可以使用:

var sorted = appointments.OrderBy(x => x.AppointmentDate);

and type inference would work out the delegate type you're interested in. 并且类型推断可以计算出您感兴趣的委托类型。

I would suggest that it's worth learning C# methodically though, rather than trying to learn it just through changes to an existing app. 我建议值得有条理地学习C#,而不是尝试仅通过更改现有应用程序来学习C#。 You could easily get into bad habits - and misunderstand fundamental language concepts - if you're not careful. 如果您不小心的话,很容易养成不良习惯,并且会误解基本的语言概念。

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

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