Benutzer:MovGP0/F♯/Classes

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      


type OrderSide = 
   | Buy
   | Sell

type OrderType = 
   | Market
   | Limit

type Order (side:OrderSide, type:OrderType, p:float) = 
   // Members
   member this.Type = type
   member this.Price = price
   
   // Properties
   let mutable _side = side
   member this.Side
      with get() = _side
      and set(side) = _side <- side
   
   // Functions
   member this.toogleOrderSide() = _side <- this.toogleOrderSide _side
   member private this.toogleOrderSide (side:OrderSide) = 
      match _side with
      | Buy -> Sell
      | Sell -> Buy

   // Operator overloading
   static member (~-) (order:Order) = 
      Order(order.toogleOrderSide(order.Side), order.Type, order.Price)

// create instance
let order = Order(Buy, Limit, 45.50)

Abstract Classes

[Bearbeiten | Quelltext bearbeiten]
module Animals

[<AbstractClass>]
type Animal (name: string) = 
    member this.Name
        with get() = name

type Giraffe (name) = 
    inherit Animal(name)

type Wolf (name) = 
    inherit Animal(name)
  • Interface members can only be accessed by upcasting
type IAnimal = 
    abstract member Name : string
        with get

type Giraffe (name) = 
    interface IAnimal with
        member this.Name 
            with get() = name

type Wolf (name) = 
    interface IAnimal with
        member this.Name 
            with get() = name
Upcast
let animal = giraffe :> Animal
Downcast
let downcastGetName (animal : Animal) = 
   match animal with
   | :? Giraffe as giraffe -> giraffe.Name
   | :? Wolf as wolf -> wolf.Name
   | _ -> String.Empty
  1. Casting and Conversions (F#). In: MSDN. Microsoft, abgerufen am 17. Juli 2014 (englisch).