So I am working on a F# project, and need to access some C# classes. In particular, one of the C# class looks like this:
class LoginRequest {
public string Scope {get; private set;}
}
Now with C# itself, an instance can be created easily with object initializer: new LoginRequest() {Scope = "all"}
for example.
However, I could not figure out a way to create such an instance from F#. Any tips?
For the given example there is no easy (non-reflection, see below) way, ie private setters are inaccessible from C# and F#:
new LoginRequest { Scope = "s" }; // CS0272 The property or indexer 'LoginRequest.Scope' cannot be used in this context because the set accessor is inaccessible
LoginRequest(Scope = "s") // error FS0495: The object constructor 'LoginRequest' has no argument or settable return property 'Scope'.
For accessing the private setter, you could use
let r = LoginRequest()
typeof<LoginRequest>.GetProperty("Scope").GetSetMethod(true).Invoke(r, [| "scope" |])
r.Scope // scope
However, I would strongly discourage the use of reflection. The most obvious reason being that you lose compile time safety.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.