C# - 如何将内联方法 Func<T> 定义为参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/156779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:03:19  来源:igfitidea点击:

C# - How do I define an inline method Func<T> as a parameter?

提问by tags2k

I've written a simple SessionItem management class to handle all those pesky null checks and insert a default value if none exists. Here is my GetItem method:

我编写了一个简单的 SessionItem 管理类来处理所有那些讨厌的空检查,如果不存在则插入一个默认值。这是我的 GetItem 方法:

public static T GetItem<T>(string key, Func<T> defaultValue)
{
    if (HttpContext.Current.Session[key] == null)
    {
        HttpContext.Current.Session[key] = defaultValue.Invoke();
    }
    return (T)HttpContext.Current.Session[key];
}

Now, how do I actually use this, passing in the Func<T> as an inline method parameter?

现在,我如何实际使用它,将 Func<T> 作为内联方法参数传入?

采纳答案by Marc Gravell

Since that is a func, a lambda would be the simplest way:

由于这是一个 func,因此 lambda 将是最简单的方法:

Foo foo = GetItem<Foo>("abc", () => new Foo("blah"));

Where [new Foo("blah")] is the func that is invoked as a default.

其中 [new Foo("blah")] 是作为默认调用的函数。

You could also simplify to:

您还可以简化为:

return ((T)HttpContext.Current.Session[key]) ?? defaultValue();

Where ?? is the null-coalescing operator - if the first arg is non-null, it is returned; otherwise the right hand is evaluated and returned (so defaultValue() isn't invoked unless the item is null).

在哪里 ??是空合并运算符 - 如果第一个参数非空,则返回;否则将评估并返回右手(因此除非项目为空,否则不会调用 defaultValue() )。

Finally, if you just want to use the default constructor, then you could add a "new()" constraint:

最后,如果您只想使用默认构造函数,那么您可以添加一个“new()”约束:

public static T GetItem<T>(string key)
    where T : new()
{
    return ((T)HttpContext.Current.Session[key]) ?? new T();
}

This is still lazy - the new() is only used if the item was null.

这仍然是懒惰的 - new() 仅在项目为空时使用。

回答by Konrad Rudolph

Why don't you pass the default value directly? What use is the functor?

为什么不直接传默认值呢?函子有什么用?

By the way, defaultValue.Invoke()is quite verbose. It's also possible to just write defaultValue().

顺便说一句,defaultValue.Invoke()很冗长。也可以只写defaultValue().

回答by Rinat Abdullin

var log = SessionItem.GetItem("logger", () => NullLog.Instance)

Note,than normally you can skip {T} specification in the GetItem{T} call (if Func{T} returns object of the same type)

请注意,通常您可以在 GetItem{T} 调用中跳过 {T} 规范(如果 Func{T} 返回相同类型的对象)