15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

FieldBuilder field = tb.DefineField ("length", typeof (int),<br />

FieldAttributes.Private);<br />

Creating a property or indexer requires a few more steps. First, call DefineProp<br />

erty on a TypeBuilder, telling it the name and type of the property:<br />

PropertyBuilder prop = tb.DefineProperty (<br />

"Text", // Name of property<br />

PropertyAttributes.None,<br />

typeof (string), // Property type<br />

new Type[0] // Indexer types<br />

);<br />

(If you’re writing an indexer, the final argument is an array of indexer types.) Note<br />

that we haven’t specified the property visibility: this is done individually on the<br />

accessor methods.<br />

The next step is to write the get and set methods. By convention, their names<br />

are csn3ed with “get_” or “set_”. You then attach them to the property by calling<br />

SetGetMethod and SetSetMethod on the PropertyBuilder.<br />

To give a complete example, we’ll take the following field and property declaration:<br />

string _text;<br />

public string Text<br />

{<br />

get { return _text; }<br />

internal set { _text = value; }<br />

}<br />

and generate it dynamically:<br />

FieldBuilder field = tb.DefineField ("_text", typeof (string),<br />

FieldAttributes.Private);<br />

PropertyBuilder prop = tb.DefineProperty (<br />

"Text", // Name of property<br />

PropertyAttributes.None,<br />

typeof (string), // Property type<br />

new Type[0]); // Indexer types<br />

MethodBuilder getter = tb.DefineMethod (<br />

"get_Text", // Method name<br />

MethodAttributes.Public | MethodAttributes.SpecialName,<br />

typeof (string), // Return type<br />

new Type[0]); // Parameter types<br />

ILGenerator getGen = getter.GetILGenerator();<br />

getGen.Emit (OpCodes.Ldarg_0); // Load "this" onto eval stack<br />

getGen.Emit (OpCodes.Ldfld, field); // Load field value onto eval stack<br />

getGen.Emit (OpCodes.Ret); // Return<br />

MethodBuilder setter = tb.DefineMethod (<br />

"set_Text",<br />

MethodAttributes.Assembly | MethodAttributes.SpecialName,<br />

null, // Return type<br />

new Type[] { typeof (string) } ); // Parameter types<br />

720 | Chapter 18: Reflection and Metadata

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!