".NET Framework Project Design" Chapter 10 Attributes

xiaoxiao2021-03-06  89

Chapter 10 Attributes

Summary:

This chapter discusses the properties and indexers in C #

First, attribute

Divided into static properties, instance properties, and virtual properties

l Avoid access directly to the type field or use the cumbersome access to access

l Good to implement the type of data package, such as changing the field and maintaining the properties of the property is transparent to the user.

l The amount of code is small, the operation is small, otherwise the method call is more appropriate.

Second, the indexer

l There are multiple overloaded indexers, as long as the parameter list is different.

l You can change the method name generated by the compiler as the indexer by applying System.Runtime.CompilerServices.IndexerNameAttribute (Default using GET_ITEM (...), set_item (...))

l Cannot define the same name and only the same name of the same reference only by the above change method name

l There is no so-called "static indexer"

Note: Adding parameters or values ​​in the attribute or indexer is worth determining to help ensure the integrity of the program.

A simple example:

Using system;

Class IndexerTest

{

Private static string [] strarr = new string [5];

IndexerTest ()

{

For (int i = 0; i <5; i )

{

Strarr [I] = i.toString ();

}

}

Public String this [int32 nindex]

{

Get {

Return strarr [NINDEX];

}

SET {

strarr [NINDEX] = VALUE;

}

}

/ / Provide different parameter columns to perform overload indexer

Public String this [byte bindex]

{

Get {

Return strarr [bindex];

}

SET {

Strarr [Bindex] = (String) Value;

}

}

// read-only properties

Public string [] strarr

{

Get {

Return strarr;

}

}

Public static void

Main

()

{

INDEXERTEST IT = New IndexerTest ();

IT [1] = "Hello"; // Written by using the indexer

FOREACH (String Str in it.strarr)

{

Console.writeLine (STR);

}

}

}

/ *

operation result:

0

Hello

2

3

4

* /

转载请注明原文地址:https://www.9cbs.com/read-122400.html

New Post(0)