使用 monad 时,结果是语言扩展的空异常

Result is null exception from language-ext when working with monads

为什么会抛出 "Result is null" 异常? None 不应该传播并设置 "a" 等于 None 吗?

public void test()
{
    Option<string> a = match(
        from b in ReturnNull()
        select b,
        x => x,
        () => null
    );
}

private Option<string> ReturnNull()
{
    return None;
}

因为 null 不是 Option<string> 的有效值。 Option 的重点是避免空值和相关的空引用异常,但是当 b 是 None:

时,您正在做的是分配空值作为结果
Option<string> a = match(
    from b in ReturnNull()
    select b,
    x => x,
    // here
    () => null
);

Option<string> where value is null is not valid, because for nulls you should use None, so it throws an exception.

Match 用于解包 Option 值,因此实际上没有理由将匹配结果分配给另一个 Option。相反,分配给基础类型变量(在本例中为 string):

string a = match(
    from b in ReturnNull()
    select b,
    x => x,
    () => null
);

或者直接使用var,因为在这种情况下match return类型是string

当然这段代码没有什么意义,因为你基本上只是扔掉 Option 和 return 回到常规的可为 null 的字符串,但我认为这只是一个例子而不是真正的代码.