C# 和 F# 转换 - 特别是“as"关键字 [英] C# and F# casting - specifically the 'as' keyword

查看:30
本文介绍了C# 和 F# 转换 - 特别是“as"关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,我可以:

In C# I can do:

var castValue = inputValue as Type1

在 F# 中,我可以:

In F#, I can do:

let staticValue = inputValue :> Type1
let dynamicValue = inputValue :?> Type1

但它们都不是 C# 的关键字 as 的等价物.

But neither of them is the equivalent of the C#'s keyword as.

我想我需要为 F# 中的等价物做一个匹配表达式

I guess I need to do a match expression for the equivalent in F#

match inputValue with
| :? Type1 as type1Value -> type1Value
| _ -> null

这是正确的吗?

推荐答案

据我所知,F# 没有任何相当于 C# 的内置运算符 as 所以你需要写一些更复杂的表达.作为使用 match 的代码的替代,您也可以使用 if,因为运算符 :? 的使用方式与 相同在 C# 中是:

As far as I know, F# doesn't have any built-in operator equivalent to C# as so you need to write some more complicated expression. Alternatively to your code using match, you could also use if, because the operator :? can be use in the same way as is in C#:

let res = if (inputValue :? Type1) then inputValue :?> Type1 else null

您当然可以编写一个函数来封装此行为(通过编写一个简单的泛型函数,该函数接受一个 Object 并将其转换为指定的泛型类型参数):

You can of course write a function to encapsulate this behavior (by writing a simple generic function that takes an Object and casts it to the specified generic type parameter):

let castAs<'T when 'T : null> (o:obj) = 
  match o with
  | :? 'T as res -> res
  | _ -> null

此实现返回 null,因此它要求类型参数具有 null 作为适当的值(或者,您可以使用 Unchecked.defaultof<'T>,相当于 C# 中的 default(T)).现在你可以只写:

This implementation returns null, so it requires that the type parameter has null as a proper value (alternatively, you could use Unchecked.defaultof<'T>, which is equivalent to default(T) in C#). Now you can write just:

let res = castAs<Type1>(inputValue)

这篇关于C# 和 F# 转换 - 特别是“as"关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆