Created
February 18, 2011 16:50
-
-
Save masaedw/833969 to your computer and use it in GitHub Desktop.
System.Attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System | |
open System.Reflection | |
// An enum of animals. | |
type Animal = | |
| Dog = 1 | |
| Cat = 2 | |
| Bird = 3 | |
// A custom attribute to allow a target to have a pet. | |
// The constructor is called when the attribute is set. | |
type AnimalTypeAttribute(pet : Animal) = | |
inherit Attribute() | |
// Keep a variable internally ... | |
let mutable thePet = pet | |
// .. and show a copy to the outside world. | |
member x.Pet | |
with get() = thePet | |
and set(v) = thePet <- v | |
// A test class where each method has its own pet. | |
type AnimalTypeTestClass() = | |
[<AnimalType(Animal.Dog)>] | |
member x.DogMethod() = () | |
[<AnimalType(Animal.Cat)>] | |
member x.CatMethod() = () | |
[<AnimalType(Animal.Bird)>] | |
member x.BirdMethod() = () | |
let main() = | |
let testClass = new AnimalTypeTestClass() | |
let typeObj = testClass.GetType() | |
for mInfo in typeObj.GetMethods() do | |
for attr in Attribute.GetCustomAttributes(mInfo) do | |
if attr.GetType() = typeof<AnimalTypeAttribute> then | |
printfn "Method %s has a pet %O attribute." | |
mInfo.Name | |
(attr :?> AnimalTypeAttribute).Pet | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment