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

查看:141
本文介绍了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#的关键字一样

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#的内置运算符 c,因此您需要编写一些更复杂的函数表达。除了使用 match 的代码之外,还可以使用 if ,因为运算符 :? 的用法与C#中的 is 相同:

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 ,因此它要求type参数具有 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天全站免登陆