本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。1.14 properties
a property is a named attribute associated with an object or a class. examples of properties include the length of a string, the size of a font, the caption of a window, the name of a customer, and so on. properties are a natural extension of fields – both are named members with associated types, and the syntax for accessing fields and properties is the same. however, unlike fields, properties do not denote storage locations. instead, properties have accessors that specify the statements to execute in order to read or write their values. properties thus provide a mechanism for associating actions with the reading and writing of an object’s attributes, and they furthermore permit such attributes to be computed.
the success of rapid application development tools like visual basic can, to some extent, be attributed to the inclusion of properties as a first-class element. vb developers can think of a property as being field-like, and this allows them to focus on their own application logic rather than on the details of a component they happen to be using. on the face of it, this difference might not seem like a big deal, but modern component-oriented programs tend to be chockfull of property reads and writes. languages with method-like usage of properties (e.g., o.setvalue(o.getvalue() + 1);) are clearly at a disadvantage compared to languages that feature field-like usage of properties (e.g., o.value++;).
properties are defined in c# using property declaration syntax. the first part of the syntax looks quite similar to a field declaration. the second part includes a get accessor and/or a set accessor. in the example below, the button class defines a caption property.
public class button: control
{
private string caption;
public string caption {
get {
return caption;
}
set {
caption = value;
repaint();
}
}
}
properties that can be both read and written, like the caption property, include both get and set accessors. the get accessor is called when the property’s value is read; the set accessor is called when the property’s value is written. in a set accessor; the new value for the property is given in an implicit value parameter.
declaration of properties is relatively straightforward, but the true value of properties shows itself is in their usage rather than in their declaration. the caption property can read and written in the same way that fields can be read and written:
button b = new button();
b.caption = "abc"; // set
string s = b.caption; // get
b.caption += "def”; // get & set
1.15 indexers
if properties in c# can be likened to “smart fields”, then indexers can be likened to “smart arrays”. whereas properties enable field-like access, indexers enable array-like access.
as an example, consider a listbox control, which displays strings. this class wants to expose an array-like data structure that exposes the list of strings it contains, but also wants to be able to automatically update its contents when a value is altered. these goals can be accomplished by providing an indexer. the syntax for an indexer declaration is similar to that of a property declaration, with the main differences being that indexers are nameless (the “name” used in the declaration is this, since this is being indexed) and that additional indexing parameters are provided between square brackets.
public class listbox: control
{
private string[] items;
public string this[int index] {
get {
return items[index];
}
set {
items[index] = value;
repaint();
}
}
}
as with properties, the convenience of indexers is best shown by looking at use rather than declaration. the listbox class can be used as follows:
listbox listbox = ...;
listbox[0] = "hello";
console.writeline(listbox[0]);
1.16 events
events permit a class to declare notifications for which clients can attach executable code in the form of event handlers. events are an important aspect of the design of class libraries in general, and of the system-provided class library in particular. c# provides an integrated solution for events.
a class defines an event by providing an event declaration, which looks quite similar to a field or event declaration but with an added event keyword. the type of this declaration must be a delegate type. in the example below, the button class defines a click event of type eventhandler.
public delegate void eventhandler(object sender, event e);
public class button: control
{
public event eventhandler click;
public void reset() {
click = null;
}
}
inside the button class, the click member can be corresponds exactly to a private field of type eventhandler. however, outside the button class, the click member can only be used on the left hand side of the += and -= operators. this restricts client code to adding or removing an event handler. in the client code example below, the form1 class adds button1_click as an event handler for button1’s click event. in the disconnect method, the event handler is removed.
using system;
public class form1: form
{
public form1() {
// add button1_click as an event handler for button1’s click event
button1.click += new eventhandler(button1_click);
}
button button1 = new button();
void button1_click(object sender, event e) {
console.writeline("button1 was clicked!");
}
public void disconnect() {
button1.click -= new eventhandler(button1_click);
}
}
the button class could be rewritten to use a property-like event declaration rather than a field-like event declaration. this change has no effect on client code.
public class button: control
{
public event eventhandler click {
get {...}
set {...}
}
public void reset() {
click = null;
}
}
1.17 versioning
versioning is an after-thought in most languages, but not in c#.
“versioning” actually has two different meanings. a new version of a component is “source compatible” with a previous version if code that depends on the previous version can, when recompiled, work with the new version. in contrast, for a “binary compatible” component, a program that depended on the old version can, without recompilation, work with the new version.
most languages do not support binary compatibility at all, and many do little to facilitate source compatibility. in fact, some languages contain flaws that make it impossible, in general, to evolve a class over time without breaking some client code.
as an example, consider the situation of a base class author who ships a class named base. in this first version, base contains no f method. a component named derived derives from base, and introduces an f. this derived class, along with the class base that it depends on, is released to customers, who deploy to numerous clients and servers.
// author a
namespace a
{
class base // version 1
{
}
}
// author b
namespace b
{
class derived: a.base
{
public virtual void f() {
system.console.writeline("derived.f");
}
}
}
so far, so good. but now the versioning trouble begins. the author of base produces a new version, and adds its own f method.
// author a
namespace a
{
class base // version 2
{
public virtual void f() { // added in version 2
system.console.writeline("base.f");
}
}
}
this new version of base should be both source and binary compatible with the initial version. (if it weren’t possible to simply add a method then a base class could never evolve.) unfortunately, the new f in base makes the meaning of derived’s f is unclear. did derived mean to override base’s f? this seems unlikely, since when derived was compiled, base did not even have an f! further, if derived’s f does override base’s f, then does derived’s f adhere to the contract specified by base? this seems even more unlikely, since it is pretty darn difficult for derived’s f to adhere to a contract that didn’t exist when it was written. for example, the contract of base’s f might require that overrides of it always call the base. derived’s f could not possibly adhere to such a contract since it cannot call a method that does not yet exist.
in practice, will name collisions of this kind actually occur? let’s consider the factors involved. first, it is important to note that the authors are working completely independently – possibly in separate corporations – so no collaboration is possible. second, there may be many derived classes. if there are more derived classes, then name collisions are more likely to occur. imagine that the base class is form, and that all vb, vc++ and c# developers are creating derived classes – that’s a lot of derived classes. finally, name collisions are more likely if the base class is in a specific domain, as authors of both a base class and its derived classes are likely to choose names from this domain.
c# addresses this versioning problem by requiring developers to clearly state their intent. in the original code example, the code was clear, since base did not even have an f. clearly, derived’s f is intended as a new method rather than an override of a base method, since no base method named f exists.
// author a
namespace a
{
class base
{
}
}
// author b
namespace b
{
class derived: a.base
{
public virtual void f() {
system.console.writeline("derived.f");
}
}
}
if base adds an f and ships a new version, then the intent of a binary version of derived is still clear – derived’s f is semantically unrelated, and should not be treated as an override.
however, when derived is recompiled, the meaning is unclear – the author of derived may intend its f to override base’s f, or to hide it. since the intent is unclear, the c# compiler produces a warning, and by default makes derived’s f hide base’s f – duplicating the semantics for the case in which derived is not recompiled. this warning alerts derived’s author to the presence of the f method in base. if derived’s f is semantically unrelated to base’s f, then derived’s author can express this intent – and, in effect, turn off the warning – by using the new keyword in the declaration of f.
// author a
namespace a
{
class base // version 2
{
public virtual void f() { // added in version 2
system.console.writeline("base.f");
}
}
}
// author b
namespace b
{
class derived: a.base // version 2a: new
{
new public virtual void f() {
system.console.writeline("derived.f");
}
}
}
on the other hand, derived’s author might investigate further, and decide that derived’s f should override base’s f, and clearly specify this intent through specification of the override keyword, as shown below.
// author a
namespace a
{
class base // version 2
{
public virtual void f() { // added in version 2
system.console.writeline("base.f");
}
}
}
// author b
namespace b
{
class derived: a.base // version 2b: override
{
public override void f() {
base.f();
system.console.writeline("derived.f");
}
}
}
the author of derived has one other option, and that is to change the name of f, thus completely avoiding the name collision. though this change would break source and binary compatibility for derived, the importance of this compatibility varies depending on the scenario. if derived is not exposed to other programs, then changing the name of f is likely a good idea, as it would improve the readability of the program – there would no longer be any confusion about the meaning of f.
1.18 attributes
c# is a procedural language, but like all procedural languages it does have some declarative elements. for example, the accessibility of a method in a class is specified by decorating it public, protected, internal, protected internal, or private. through its support for attributes, c# generalizes this capability, so that programmers can invent new kinds of declarative information, specify this declarative information for various program entities, and retrieve this declarative information at run-time. programs specify this additional declarative information by defining and using attributes.
for instance, a framework might define a helpattribute attribute that can be placed on program elements such as classes and methods to provide a mapping from program elements to documentation for them. the example
[attributeusage(attributetargets.all)]
public class helpattribute: system.attribute
{
public helpattribute(string url) {
this.url = url;
}
public string topic = null;
private string url;
public string url {
get { return url; }
}
}
defines an attribute class named helpattribute, or help for short, that has one positional parameter (string url) and one named argument (string topic). positional parameters are defined by the formal parameters for public constructors of the attribute class; named parameters are defined by public read-write properties of the attribute class. the square brackets in the example indicate the use of an attribute in defining the help attribute. in this case, the attributeusage attribute indicates that any program element can be decorated with the help attribute.
the example
[help("http://www.mycompany.com/…/class1.htm")]
public class class1
{
[help("http://www.mycompany.com/…/class1.htm", topic ="f")]
public void f() {}
}
shows several uses of the attribute.
attribute information for a given program element can be retrieved at run-time by using the .net runtime’s reflection support. the example
using system;
class test
{
static void main() {
type type = typeof(class1);
object[] arr = type.getcustomattributes(typeof(helpattribute));
if (arr.length == 0)
console.writeline("class1 has no help attribute.");
else {
helpattribute ha = (helpattribute) arr[0];
console.writeline("url = {0}, topic = {1}", ha.url, ha.topic);
}
}
}
checks to see if class1 has a help attribute, and writes out the associated topic and url values if the attribute is present.