Reputation: 13089
I have this interface:
interface IHaveHeaders {
Dictionary<string, object>? Headers { get; set; }
void SetHeader(string key, object value);
object? GetHeader(string key);
}
I'm trying to implement it in F# and access the Headers
Dictionary in the SetHeader
and GetHeader
functions but I don't know how to access the Headers
member from the functions:
type HeadersImpl =
interface IHaveHeaders with
member val Headers = Dictionary<string, obj>() with get, set
member this.SetHeader (key, value) = () // how do I add a new `Headers` entry?
member this.GetHeader (key) = null // how do I get an entry from `Headers`
Upvotes: 1
Views: 65
Reputation: 243051
The answer from Philip will certainly do the trick. An alternative approach would be to not use automatic property for Headers
, but instead define a local field explicitly. This makes your property definition a bit longer, but it makes the access code a lot simpler:
type HeadersImpl() =
let mutable headers = Dictionary<string, obj>()
interface IHaveHeaders with
member this.Headers with get() = headers and set(v) = headers <- v
member this.SetHeader (key, value) = headers.Add(key, value)
member this.GetHeader (key) = headers.[key]
Upvotes: 4
Reputation: 5005
Since F# doesn't support implicit upcasting as of this answer, you need to explicitly upcast to the interface type on this
.
type HeadersImpl =
interface IHaveHeaders with
member val Headers = Dictionary<string, obj>() with get, set
member this.SetHeader (key, value) =
let headers = (this :> IHaveHeaders).Headers
headers.Add(key, value)
member this.GetHeader (key) =
let headers = (this :> IHaveHeaders).Headers
headers.[key]
Upvotes: 4