简体   繁体   English

正确地将C#默认字符串分配给F#变量

[英]Correctly assigning C# default String to F# variable

As a part of rewriting my C# code in F# I have come across the situation where I do not know how to best handle the default values of the System.String type returned from a C# service. 作为用F#重写C#代码的一部分,我遇到了一种情况,即我不知道如何最好地处理从C#服务返回的System.String类型的默认值。

The C# equivalent of what I would like to do would be: 我想做的等效于C#:

var myCSharpString = CSharpService.GetCSharpString() ?? "";

Simply put, if the string returned by GetCSharpString is null or default(string), I would like it to be set to " " instead. 简而言之,如果GetCSharpString返回的字符串为null或default(string),我希望将其设置为“”。

However, what will happen if I try to do the following statement in F#? 但是,如果我尝试在F#中执行以下语句会发生什么?

let myFSharpString = CSharpService.GetCSharpString

In the case where GetCSharpString returns null or default(string), will myFSharpString be the default value of strings in F# (that is: " ")? 在GetCSharpString返回null或default(string)的情况下,myFSharpString是F#中字符串的默认值(即“”)吗? Or will I have to explicitly do a null check, such as: 还是我必须显式地进行null检查,例如:

let myFSharpString =
    match CSharpService.GetCSharpString with
    | val when val = Unchecked.defaultof<System.String> -> ""
    | val -> val

I have found myself to do checks such as this several times, and I simply cannot get over the fact of how much code is needed for such a simple task. 我发现自己已经做过几次这样的检查,而我根本无法克服这样一个简单任务需要多少代码的事实。

Could someone enlighten me of whether such null checks are actually needed in F# when dealing with C# services that returns System.String? 有人可以启发我在处理返回System.String的C#服务时F#中是否实际上需要这种空检查吗?

Update : 更新

I am not asking about the ??-operator in the combination with the F#'s Option type, as has been answered before in this post. 我不是在与F#的Option类型结合使用??运算符,而是在本文中回答过的。 Rather I am asking about how to handle the C# null value of strings in an F# context. 而是我在问如何在F#上下文中处理字符串的C#空值。

Another seemingly possible answer I have tried, would be to make a custom operator, such as: 我尝试过的另一个看似可行的答案是创建一个自定义运算符,例如:

let inline (|??) (a: 'a Nullable) b = if a.HasValue then a.Value else b

This, however, gives a compile error, since F# interprets the return value of GetCSharpString as of type 'string', which in F# is NotNullable. 但是,这会产生编译错误,因为F#会将GetCSharpString的返回值解释为类型为“字符串”的类型,在F#中该类型为NotNullable。

Define a function and a single-case active pattern: 定义一个函数和一个单例活动模式:

let safeStr = function
    | null -> String.Empty
    | x -> x
let (|SafeStr|) = safeStr

You can now use either the function: 您现在可以使用以下任一功能:

let myFSharpString = safeStr <| CSharpService.GetCSharpString()

... or the active pattern: ...或活动模式:

let processCSharpString (SafeStr x) =
    // x is never null :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM