F# upcasting TextBlock to UIElement
What is wrong with:
let (x:UIElement) = upcast new TextBlock()
The error is: The type 'System.ComponentModel.ISupportInitialize' is required here and is unavailable. You must add a reference to assembly 'System, Version=4.0.0....'
TextBlock
is a subtype of UIElement
...
Note that doing what the error message says does solve the issue, but why is that necessary to do 开发者_StackOverflow社区something as basic as upcasting?
As lasseespeholt mentioned in his (now deleted?) answer, there is nothing wrong with your code and you just need to add the reference to System.dll
as the error message suggests.
But what is going on?
You are getting the error message on that particular line, because it is the first place where the compiler encounters some type from the System.dll
library (an interface ISupportInitialize
, which is implemented by TextBlock
) and realizes that it needs the reference to the library in order to understand the type.
Another way to get the same error message is to write this:
let x = new TextBlock()
x. // If you get IntelliSense here, you'll see just '<Note>'
// with the same error message as the one you're getting
In this case, the IntelliSense needs to look at the type (so that it can populate member completion).
From the documentation:
"In many object-oriented languages, upcasting is implicit; in F#, the rules are slightly different. Upcasting is applied automatically when you pass arguments to methods on an object type. However, for let-bound functions in a module, upcasting is not automatic, unless the parameter type is declared as a flexible type. For more information, see Flexible Types (F#)."
If you'd use the following syntax:
let (x:#UIElement) = new TextBlock()
your code would use a flexible type (indicated by the #
) and it would compile. However, now you would get a warning:
"This construct causes code to be less generic than indicated by its type annotations. The type variable implied by the use of a '#', '_' or other type annotation at or near 'c:\path\Program.fs' has been constrained to be type 'TextBlock'."
精彩评论