【发布时间】:2019-09-24 08:33:35
【问题描述】:
我正在试用新的Nullable Reference Types in C# 8.0,但遇到了以下问题。
鉴于此结构:
public readonly struct Either<TReturn, TError>
where TReturn : struct
where TError : struct
{
public TError? Error { get; }
public TReturn? Response { get; }
public Either(TError? error, TReturn? response)
{
if (error == null && response == null)
{
throw new ArgumentException("One argument needs not to be null.");
}
if (error != null && response != null)
{
throw new ArgumentException("One argument must be null.");
}
Error = error;
Response = response;
}
}
我如何告诉编译器 either Error 或 Response 不为空,并且它们不能两者都为空?有没有办法用新属性做这样的事情?
【问题讨论】:
-
Either与 NRT 无关,这不完全是Either- 它只是一种类型而不是两种。现在最相关的功能是开关表达式和模式匹配。例如result switch { OK<TReturn> response=>...,Error<TError> error=>...}。您必须等待 C# 9 和可区分的联合来实现真正的 Either -
顺便说一句,
Either模式是什么意思?当我听到它时,我想到了 F#、模式匹配和 DI。 -
我不知道这是否是一种模式,但更像是错误处理medium.com/techtron/functional-errors-handling-1d1b4688769d 的常见做法。我只是想知道,鉴于我们得到的奇特属性,是否有人能够说些什么:它要么将 this 作为非空返回,要么将其作为非空返回。我怀疑如果有,它可能会通过一个简单的结构来支持,比如我的问题中的结构,属性在正确的位置。
-
你可以称之为模式或成语。这不仅仅是一种常见的做法。更好的参考是 F#'s Result type 和 Scott Wlaschin 的 Railway-Oriented programming。 Scott Wlaschin 的文章比之后的文章更好地解释了这一点
-
Is there a way to do such a thing with the new attributes ?号
标签: c# nullable c#-8.0 nullable-reference-types