C # attributes with parameters (Indexer)

Source: Internet
Author: User

 

For details about the parameter-free attributes, refer to comparison.

Today I flipped through the book to see what is the difference between the property of a parameter (Indexer) and the property of a non-parameter.

The get accessors method of attributes does not accept parameters. Therefore, we call these attributes a non-parameter attribute, because they are similar to field access, so these attributes are easy to understand.

In addition to these attributes similar to field access, C # also supports parameter attributes (Indexer). Its get accesser method accepts one or more parameters, the set accessors method accepts two or more parameters.

C # The array-style syntax is used to expose the property of parameters. You can regard the indexer as a method for C # to overload the [] operator.

Class test

{

Private int [] nums;

Private int length;

Public string sss

{

Get;

Set;

}

Public test (int len)

{

If (len <= 0)

{

Console. WriteLine ("input an integer greater than 0 ");

Throw new ArgumentOutOfRangeException ("an integer greater than 0! ");

}

Length = len;

Nums = new int [length];

}

// [IndexerName ("Nums")]

Public int this [int post]

{

Get {if (post <0 | post> = length) {Console. WriteLine .. "); Throw new ArgumentOutOfRangeException (" post ");} else {return nums [post];}

Set {if (post> = 0 & post <length & nums! = Null) {nums [post] = value;} else {throw new ArgumentOutOfRangeException ("post", post. ToString ());}}

}

Public string this [int I, string s]

{

Get {return "";}

Set {}

}

}

Class Program

{

Static void Main ()

{

PropertyInfo [] propertys = typeof (test). GetProperties ();

Foreach (PropertyInfo p in propertys)

{

Console. WriteLine ("GetMethod Name: {0}, SetMethod Name: {1}", p. GetGetMethod (). Name, p. GetSetMethod (). Name );

}

Test t = new test (15 );

For (int I = 0; I <15; I ++)

{

T [I] = I + 1;

Console. WriteLine (t [I]);

}

Console. ReadKey ();

}

 

}

 

All indexers must have at least one parameter and can have more. These parameters and return types can be of any type other than void. In the System. Drawing. Imaging. ColorMatrix class, an example of an indexer with multiple parameters is provided. For details, refer:

Public float this [int row, int column]

{

Get

{

Return this. GetMatrix () [row] [column];

}

Set

{

Float [] [] numArray;

NumArray = this. GetMatrix ();

NumArray [row] [column] = value;

This. SetMatrix (numArray );

Return;

}

}

 

You often need to create an index to query the values in the associated array. collections. generic. the Dictionary class provides an indexer that obtains a value and returns the value associated with the key.

Public TValue this [TKey key]

{

Get

{

Int num;

TValue local;

Num = this. FindEntry (key );

If (num <0)

{

Goto Label_001E;

}

Return & (this. entries [num]). value;

Label_001E:

ThrowHelper. ThrowKeyNotFoundException ();

Return default (TValue );

}

Set

{

This. Insert (key, value, 0 );

Return;

}

}

 

 

Different from the parameter-free attribute, the type can provide multiple overloaded indexers, as long as the signatures of these indexers are different.

CLR itself does not distinguish between non-parameter attributes and parameter attributes. For CLR, attributes are some methods and metadata defined in the type. C # Only Allows defining the indexer on the object instance. C # does not provide syntax for defining the attributes of the static indexer, but CLR supports static parameters.

Since the C # indexer syntax does not allow the openers to specify the name of the indexer, the compiler selects a default name for the indexer. If you have noticed it, you should find it: the name of the method generated by the compiler is get_Item and set_Item. The first code can be found.

 

Using C # will never see the Item name, so you generally do not need to care about the name selected by the compiler. However, if the indexer is designed for a type and has code access from other languages, you may need to change the default Item Name Of The indexer. C # allows you to apply System. Runtime. ComplierServices. IndexerNameAttribute To The indexer to rename these methods.

[IndexerName ("Nums")]

Public int this [int post]

{

Get {if (post <0 | post> = length) {Console. WriteLine .. "); Throw new ArgumentOutOfRangeException (" post ");} else {return nums [post];}

Set {if (post> = 0 & post <length & nums! = Null) {nums [post] = value;} else {throw new ArgumentOutOfRangeException ("post", post. ToString ());}}

}

Public string this [int I, string s] // If IndexerName is not used to change the default Item to Nums, an error is returned: "the names of the two indexers are different; the same name must be used for the IndexerName feature on each indexer of the type." Multiple indexers can be defined in one type, as long as the parameter set of The indexer is different. In other languages, the IndexerName attribute allows multiple indexers with the same signature to be defined, each indexer has different names, but this is not allowed in C # because its syntax does not reference the indexer by name.

{

Get {return "";}

Set {}

}

 

Www.2cto.com

Here, the compiler will generate a method named get_Nums and set_Nums, instead of the default one. If the Code contains multiple parameters with different names, C # cannot compile the code.

C # The indexer is an overload method for [] operators, and the [] Operator cannot be used to eliminate the ambiguity of parameter attributes with different method names and the same parameter set.

If you have not pointed out the attributes with or without parameters, you are welcome to make common progress... Pai_^

Author: in vain

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.