X hits on this document





44 / 396

Chapter ‎18   Unsafe code

static double[] Apply(double[] a, Function f) { double[] result = new double[a.Length]; for (int i = 0; i < a.Length; i++) result[i] = f(a[i]); return result; }

static void Main() { double[] a = {0.0, 0.5, 1.0};

double[] squares = Apply(a, new Function(Square));

double[] sines = Apply(a, new Function(Math.Sin));

Multiplier m = new Multiplier(2.0); double[] doubles =  Apply(a, new Function(m.Multiply)); } }

An instance of the Function delegate type can reference any method that takes a double argument and returns a double value. The Apply method applies a given Function to the elements of a double[], returning a double[] with the results. In the Main method, Apply is used to apply three different functions to a double[].

A delegate can reference either a static method (such as Square or Math.Sin in the previous example) or an instance method (such as m.Multiply in the previous example). A delegate that references an instance method also references a particular object, and when the instance method is invoked through the delegate, that object becomes this in the invocation.

An interesting and useful property of a delegate is that it does not know or care about the class of the method it references; all that matters is that the referenced method has the same parameters and return type as the delegate.

1.12 Attributes

Types, members, and other entities in a C# program support modifiers that control certain aspects of their behavior. For example, the accessibility of a method is controlled using the public, protected, internal, and private modifiers. C# generalizes this capability such that user-defined types of declarative information can be attached to program entities and retrieved at runtime. Programs specify this additional declarative information by defining and using attributes.

The following example declares a HelpAttribute attribute that can be placed on program entities to provide links to their associated documentation.

using System;

public class HelpAttribute: Attribute { string url; string topic;

public HelpAttribute(string url) { this.url = url; }

public string Url { get { return url; } }

public string Topic { get { return topic; } set { topic = value; } } }

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.31

Document info
Document views497
Page views497
Page last viewedMon Oct 24 04:10:21 UTC 2016