gpt4 book ai didi

.net - F#方法返回null而不是Option

转载 作者:行者123 更新时间:2023-12-04 13:46:37 24 4
gpt4 key购买 nike

我在F#上开发.net 4.6.1应用程序VS2015。我有方法:

type CommonHelper = 
static member SideEffectOnNull act x = if x = null then act(); x else x
static member SideEffectOnNotNull act x = if x <> null then act(); x else x

...
    static member GetPerformanceCounter ( fname: CounterFullName ) = 

let getCounterInternal ( counterFullName: CounterFullName ) =
Log.Information("Getting counter: {category}\\{name}\\{instance} ", counterFullName.Category, counterFullName.Name, counterFullName.Instance)
let receivedCategory = PerformanceCounterCategory.GetCategories().FirstOrDefault( fun x -> String.Equals( x.CategoryName, counterFullName.Category.Category, StringComparison.InvariantCultureIgnoreCase ) )
if receivedCategory = null then
Serilog.Log.Warning ( "Category not found: {category}", counterFullName.Category ); null
else
let receivedCounters = PerforrmanceCounterProxy.GetPerformanceCountersFromCategoryOrNull counterFullName.Instance receivedCategory
if receivedCounters = null then
Log.Warning ("Instance not found {name}(instance: {instance}) in category {category}", counterFullName.Name, counterFullName.Instance, counterFullName.Category); null
else
receivedCounters.FirstOrDefault( fun y -> String.Equals( y.CounterName, counterFullName.Name.Name, StringComparison.InvariantCultureIgnoreCase ) )
|> CommonHelper.SideEffectOnNull ( fun unit -> Log.Warning ("Name {name}(instance: {instance}) not found for category {category}", counterFullName.Name, counterFullName.Instance, counterFullName.Category) )

getCounterInternal fname
|> CommonHelper.SideEffectOnNull (fun unit ->Log.Warning( "Getting counter failed: {category}\\{name}\\{instance}", fname.Category, fname.Name, fname.Instance ))
|> CommonHelper.SideEffectOnNotNull (fun unit ->Log.Information( "Getting Counter secceed: {category}\\{name}\\{instance}", fname.Category, fname.Name, fname.Instance ))
|> (fun x -> if x = null then None else Option.Some(x))

但是当我调用此方法时,我收到的是 null而不是 option
enter image description here
我做错了什么?

最佳答案

在F#中,可以在运行时用null常数表示DU的一个无数据值。您可以使用CompilationRepresentationFlags.UseNullAsTrueValue指示编译器执行此操作:

[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
type A = B | C of int

printfn "%A" (obj.ReferenceEquals( B, null )) // will print "true"

在上面的代码中,DU值 B被编译为 null。有时出于优化目的是很好的:我不是每次都分配实例,而是使用一个常量。如果该值使用率很高,则有帮助。

因此, Option类型在 None情况下使用了相同的技术,这就是为什么 None在调试器中显示为 null的原因。

有一天,调试器将具有适当的扩展点,以实现此功能和其他F#功能。在此之前,调试器会讲C#,然后您就可以进行翻译了。

关于.net - F#方法返回null而不是Option,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41337310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com