【问题标题】:Need help writing an anonymous method?需要帮助编写匿名方法吗?
【发布时间】:2011-09-12 14:17:57
【问题描述】:

如果我的问题在技术上措辞有误,请原谅我,但我基本上需要一个匿名方法或 Func 委托来封装以下功能:

                if (Cache.CurrentCustomer == null)
                {
                    return null;
                }
                else
                {
                    return Cache.CurrentCustomer.PersonID; // (Guid type)
                }

上述 if 语句将返回一个值,该值将分配给 Order 实体,该实体具有公开的 PersonID 属性字段,该字段接受可为空的 guid 类型。

如果一个 Func 委托是可能的,那么可以像这样动态实例化:

orderToInsert.PersonID = new Func() => { ... }

我通常会将我的 if 语句场景发送到帮助支持方法中,这是学习我多年来一直在尝试选择的东西的好机会!蒂亚!!!

【问题讨论】:

  • () => (Guid?)Cache.CurrentCustomer.PersonID

标签: c# .net-4.0 anonymous-methods


【解决方案1】:

这里是 lambda 形式:

Func<Guid?> lambda = () => Cache.CurrentCustomer == null 
                             ? (Guid?)null 
                             : Cache.CurrentCustomer.PersonID;

然后你会像 in 一样使用它

orderToInsert.PersonID = lambda();

更新:如果您只是想看看这里有什么可能,那么您也可以这样做:

orderToInsert.PersonID = (() => Cache.CurrentCustomer == null 
                             ? (Guid?)null 
                             : Cache.CurrentCustomer.PersonID)();

这实际上只是做经典的一种迂回方式:

orderToInsert.PersonID = Cache.CurrentCustomer == null 
                             ? (Guid?)null 
                             : Cache.CurrentCustomer.PersonID;

【讨论】:

  • TY 用于快速响应,但我可以按照问题后半部分的描述使用它吗? ------------ 基本上我只是想知道这就是我通常只使用计划方法的全部内容。我想我知道如何内联使用它,让我试试看。
  • @IbrarMumtaz:我不明白你想在这里做什么。与我们在这里所做的不同,您到底想做什么?
  • 基本上我想使用你写的表达式,但内联声明和使用它。我认为这是一种现在学习的有用技术,也许可以在我项目的其他领域使用它。
  • 非常感谢我最终使用了经典版本。
猜你喜欢
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
相关资源
最近更新 更多