Nullable Func<T, TResult>

本文关键字:TResult gt lt Nullable Func | 更新日期: 2023-09-27 18:34:17

在C#中,是否可以向方法传递可为空的Func?

Func<A, bool>?Func?<A, bool>都不起作用。

Nullable Func<T, TResult>

这没有意义。
所有引用类型(包括 Func<...> )都可以null

可为空的类型适用于通常不能null的值类型 ( struct s)。

Func 是一个委托,它是一个引用类型。这意味着它已经可为空(您可以将 null 传递给方法)。

Func -> 封装一个返回由泛型参数指定的类型的方法

如果返回类型为 void,则存在不同的委托(操作)

操作 ->封装不返回值的方法。

如果要求 Func 接受可以接受 null(可为

空的类型)的参数,或者要求 Func 返回可能是 null(可为空的类型)的值,则没有限制。

例如。

    Func<int?, int?, bool> intcomparer = 
    (a,b)=>
    {
    if(a.HasValue &&b.HasValue &&a==b) 
        return true;
        return false;
    } ;
    Func<int?, int?, bool?> nullintcomparer = 
    (a,b)=>
    {
    if(a.HasValue &&b.HasValue &&a==b) 
        return true;
    if(!a.HasValue || !b.HasValue)
       return null;
        return false;
    } ;
    var result1 = intcomparer(null,null); //FALSE
    var result2 = intcomparer(1,null); // FALSE
    var result3 = intcomparer(2,2); //TRUE

    var result4 = nullintcomparer(null,null); // null
    var result5 = nullintcomparer(1,null); // null
    var result6 = nullintcomparer(2,2); //TRUE

C# 1.0 - 7.x:

默认情况下,包括 Func 作为委托的所有引用类型都可以为 null。

C#> 8.x:

Func<T>必须标记为Func<T>?才能接收null作为默认参数值。

C# 1.0 - 7.x 的示例:

/// <summary>
/// Returns an unique absolute path based on the input absolute path.
/// <para>It adds suffix to file name if the input folder already has the file with the same name.</para>
/// </summary>
/// <param name="absolutePath">An valid absolute path to some file.</param>
/// <param name="getIndex">A suffix function which is added to original file name. The default value: " (n)"</param>
/// <returns>An unique absolute path. The suffix is used when necessary.</returns>
public static string GenerateUniqueAbsolutePath(string absolutePath, Func<UInt64, string> getIndex = null)
{
    if (getIndex == null)
    {
        getIndex = i => $" ({i})";
    }
    // ... other logic
}

>C# 8.x 的示例:

/// <summary>
/// Returns an unique absolute path based on the input absolute path.
/// <para>It adds suffix to file name if the input folder already has the file with the same name.</para>
/// </summary>
/// <param name="absolutePath">An valid absolute path to some file.</param>
/// <param name="getIndex">A suffix function which is added to original file name. The default value: " (n)"</param>
/// <returns>An unique absolute path. The suffix is used when necessary.</returns>
public static string GenerateUniqueAbsolutePath(string absolutePath, Func<UInt64, string>? getIndex = null)
{
    if (getIndex == null)
    {
        getIndex = i => $" ({i})";
    }
    // ... other logic
}