English 中文(简体)
F#类型检查出现意外结果
原标题:Unexpected result with F# type check
  • 时间:2023-06-23 02:01:49
  •  标签:
  • f#

为什么这两个函数(f1和f2)返回不同的结果?

let f1< t>() = if typeof<byte[]> = typeof< t> then printfn "Is Byte Array" else printfn "Is Not Byte Array"

let f2< t>() =
    match box Unchecked.defaultof< t> with
    | :? (byte[]) -> printfn "Is Byte Array" 
    | _ -> printfn "Is Not Byte Array"

f1<byte[]>();;
Is Byte Array

f2<byte[]>();;
Is Not Byte Array
问题回答

因为未选中.defaultof<;t>总是返回null

> Unchecked.defaultof<byte[]>;;
val it: byte array = <null>

> Unchecked.defaultof<int>;;
val it: int = 0

> Unchecked.defaultof<string>;;
val it: string = <null>

> Unchecked.defaultof<int * bool>;;
val it: int * bool = <null>

> Unchecked.defaultof<bool>;;
val it: bool = false

这就是“未检查”部分应该传达的意思。不检查此值是否正确/有效。如果你使用这些函数,你会更好地知道你在做什么。

除了Fyodor的答案之外,null值不携带运行时类型信息,这意味着一旦它被装箱,就不能再强制转换回byte[]。您甚至不用调用<code>Unchecked.defaultof

let f3() =
    let x : byte[] = null
    match box x with
    | :? (byte[]) -> printfn "Is Byte Array" 
    | _ -> printfn "Is Not Byte Array"
    
f3 ();;
Is Not Byte Array




相关问题
F#: Storing and mapping a list of functions

I have a number of events that happen in a game. I want to control the time and order at which these events occur. For example: Event 1: Show some text on screen for N frames & play a sound ...

Creating Silverlight 3 applications with F#

Is there an easy way to create Silverlight 3 applications with F# (October CTP)? I have seen the F# for Silverlight, but that only works with the May CTP. I am using Visual Studio Integrated Shell ...

How To Change List of Chars To String?

In F# I want to transform a list of chars into a string. Consider the following code: let lChars = [ a ; b ; c ] If I simply do lChars.ToString, I get "[ a ; b ; c ]". I m trying to get "abc". I ...

Unzipping ZLIB compressed portions of a binary file

I m reading a file(a flash swf) from .Net 3.5 that has a header which states whether the body of the file/Stream is compressed or not. However, I m having problems-after I rewrap the basic File ...

Pretty print a tree

Let s say I have a binary tree data structure defined as follows type a tree = | Node of a tree * a * a tree | Nil I have an instance of a tree as follows: let x = Node (Node (...

F# String Pattern-Matching with Wildcards

As part of a project I have assigned myself as a way of improving my knowledge of F# and functional programming in general, I am attempting to write a string pattern-matching algorithm from scratch ...