Easy to write with C #. NET components

Source: Internet
Author: User
Tags constructor exception handling garbage collection

Before the. NET Framework was presented, writing components was seen as a job that required deep skill and was daunting to many people. The presence of. NET makes the authoring of components so approachable, while the. NET Framework's core language, C #, is called a component-oriented language. Here, I'll show you how to use C # to write components that run in a. NET Framework environment, including how to write component classes, how to add fields, properties, and events, and how to compile and distribute components.







First look at this simple enough code example (we'll slowly turn it into a spite component later):

Using System;
Namespace Componentcs
{
public class StringComponent
{
Private string[] Stringsset;
public int Stringlength
{
Get
{
return stringsset.length;
}
}
public void Modify (int index,string value)
{
if ((Index < 0) | | (index >= stringsset.length))
{
throw new IndexOutOfRangeException ();
}
Else
{
Stringsset[index]=value;
OnModify ();
}
}
Public StringComponent ()
{
Stringsset = new string[]
{
"C # String 0",
"C # String 1",
"C # String 2",
"C # String 3"
};
}
public string GetString (int index)
{
if ((Index < 0) | | (index >= stringsset.length))
{
throw new IndexOutOfRangeException ();
}
return Stringsset[index];
}
}
}

Generally, we first create a namespace (namespace) to encapsulate a series of classes in this component:

Namespace Compcs

The namespace is very flexible to use, it can be nested, you can write its internal classes in multiple files, and, correspondingly, you can declare multiple nested namespaces in one source file. The following is a sample code that uses a nested namespace:

Namespace nestit{namespace Nestednamespace {class MyClass {public static void Dosth () {...}}}}

You can quote class MyClass like this:

nestit.nestednamespace.myclass.dosth ();

or back to our namespace compcs, we declare a class stringcomponent using the following statement:

public class StringComponent

A class in a namespace is required because all of the code in C # must be encapsulated in a class, so there is no value to the namespace of the class.

Below we add a common (public) domain for this class:

private string[] Stringsset;

In addition, it may also need to define some attributes, following is an example of defining a read-only attribute:

public int stringlength{get {return stringsset.length;}}

The attributes in c# more fully embody the encapsulation of the object, not directly manipulate the data content of the class but through the accessor, which uses the get and set accessors to read and write the value of the property. In C + +, this is a job that requires a programmer to do it manually.

In the access declaration of the attribute:

. Only the set accessor indicates that the value of the property can only be set and cannot be read

. Only get accessor indicates that the value of the property is read-only and cannot be overwritten

. Both a set accessor and a get accessor indicate that the value of the property is read and written to be allowed

You may find that domains and attributes are so similar, true the syntax of a property is similar to that of a field, but they are absolutely different, except that you cannot use a property as a variable or pass a property as a reference parameter or an output parameter, instead, for a domain, there is no such restriction.

The following code defines the constructor for this class:

public StringComponent ()

The # constructor must have the same name as the class, it can be overloaded, but it cannot have a return value, so it does not return a value type prefix. When a user creates an instance of a new class, the constructor is executed automatically, and the garbage collection mechanism of C # starts to manage the instance, and the resource is reclaimed at the appropriate time.
We then write a getstring () function that returns the corresponding record based on the index value passed in by the user:

public string GetString (int index)
{... return stringsset[index];}

What to note is the method of exception handling:

throw new IndexOutOfRangeException ();

As a robust component, the exception handling mechanism is essential, although it may consume some resources, but the increased security will make you feel that the resources consumed are negligible. A system-defined exception class IndexOutOfRangeException () is used here, and in fact, more often than not, you have to define the exception class yourself to accommodate a variety of different situations. The following code example shows how to define an exception class:

public class myapplicationexception:applicationexception{public string amsg;
Public myapplicatonexception (String strMsg)
{
amsg=strmsg;
}
}

The only difference between defining an exception class and defining a normal class is that the exception class must inherit from the System.Exception class. In fact, Microsoft recommends that all user-defined exception classes be used as subclasses of the ApplicationException class. Put the class myapplicationexception in the namespace compcs so you can overwrite the exception handling in the GetString () function. The following is a GetString () method with a more complete exception handling mechanism:

public string GetString (int index) {try {if (Index < 0) | | (index >= stringsset.length)) {throw new Myapplicationexception ("parameter out of Range");} The catch (Myapplicationexception Merr) {Console.WriteLine (merr.amsg);} catch (Exception Err) {Console.WriteLine ( Err.message); }
return Stringsset[index];
}

In a similar way, you can handle a much more complicated situation.

Below, let's consider adding events to this class. The introduction of event mechanisms allows developers to develop programs more flexibly. The following code example shows how to define an event:

public event EventHandler Modified;

Use the event keyword in C # to define events. Put this definition into our class componentcs.stringcomponent, and then we add a function modify (), which modifies the value at the specified position in the character array Stringsset and raises the OnModify event. In the Modify event, we call the function specified by the event modified:

public void Modify (int index,string value) {if (Index < 0) | | (index >= stringsset.length)) {throw new IndexOutOfRangeException ();} else {stringsset[index]=value; OnModify (); } }
private void OnModify ()
{
EventArgs e=new EventArgs ();
if (!) ( Modified==null))
Modified (this,e);
}

Then we can invoke the following method:

private void DoIt () {stringcomponent mysc=new stringcomponent (); Mysc. Modified+=new EventHandler (called); Mysc. Modify (2, "another string"); public void called (Object O,eventargs e) {Console.WriteLine ("Changed");}


In function doit (), we first set up an object MYSC for the StringComponent class, and then associate its Mofidied event to the called () method:

mysc. Modified+=new EventHandler (called);

Note the use of the "+ +" symbol, conversely, if you use the "-=" symbol, you can cancel the binding of this event.

Now we have a simple, but relatively complete component class:

Using System;
Namespace Componentcs
{
public class StringComponent
{

Private string[] Stringsset;
public event EventHandler Modified;
public int Stringlength
{
Get
{
return stringsset.length;
}
}
public void Modify (int index,string value)
{
if ((Index < 0) | | (index >= stringsset.length))
{
throw new IndexOutOfRangeException ();
}
Else
{
Stringsset[index]=value;
OnModify ();
}
}
private void OnModify ()
{
EventArgs e=new EventArgs ();
if (!) ( Modified==null))
Modified (this,e);
}
Public StringComponent ()
{
Stringsset = new string[]
{
"C # String 0",
"C # String 1",
"C # String 2",
"C # String 3"
};
}
public string GetString (int index)
{
if ((Index < 0) | | (index >= stringsset.length))
{
throw new IndexOutOfRangeException ();
}
return Stringsset[index];
}
}
}


The last thing to do is to compile it into a. dll (dynamic-link library) file for publication. The biggest benefit of publishing to a. dll file is that the content in the. dll file has been compiled, which can greatly speed up the program, and protect the source code.

The resulting. cs file is compiled into a. dll file as follows:

csc.exe/t:library/debug+/out:mycom.dll Example.cs

This will output a. dll file named MyCom.dll.

ok, we have completed a component, though small, spite, which is the basis of all components, the whole process will not take 10 minutes.
Of course, if it is a component with real value, we have to consider much more than that, but we can see that C # 's strong support for components can greatly improve our development efficiency, so that we have more focus on algorithmic design and so on, to develop more outstanding components.



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.