Use C # To easily write. Net components

Source: Internet
Author: User

Before the. net Framework was put forward, writing components was regarded as a kind of work that requires advanced skills, which made many people daunting. The emergence of. net makes component compilation so approachable. The core language C # Of. net framework is also called component-oriented language. Here, I will show you how to use C # to write in. components running in the. net framework environment, including how to compile component classes, how to add domains, attributes, and events, and how to compile and distribute components.

First, let's take a look at the following simple code example (we will gradually turn it into a dirty 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 to encapsulate a series of classes in this component:

Namespace CompCS

The namespace is very flexible to use. It can be nested, or its internal classes can be written in multiple files, correspondingly, you can also declare multiple non-nested namespaces in a source file. The following is an example code of using nested namespaces:

Namespace NestIt {namespace NestedNameSpace {class myClass {public static void dosomething (){...}}}}

You can reference the class myClass as follows:

NestIt. NestedNameSpace. myClass. dosomething ();

Back to our namespace CompCS, we declared a class StringComponent using the following statement:

Public class StringComponent

Classes in a namespace are required because all code in C # Must be encapsulated in classes, so namespace without classes has no value.

Next we will add a public domain for this class:

Private string [] StringsSet;

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

Public int StringLength {get {return StringsSet. Length ;}}

The properties in C # fully reflect the encapsulation of objects. Instead of directly operating the data content, they are accessed through the accessors, it reads and writes the attribute values with get and set accessors. In C ++, this is a task that requires programmers to do manually.

In the attribute access declaration:

. Only set accessors indicate that the attribute values can be set but cannot be read.

. Only get accessors indicate that the attribute value is read-only and cannot be rewritten.

Both set accessors and get accessors indicate that the read and write operations on the attribute values are allowed.

You may find that the fields and attributes are so similar that they are indeed similar to the syntax of the domain, but they are absolutely different. The difference is that you cannot use attributes as variables, you cannot pass attributes as reference parameters or output parameters. On the contrary, there are no such restrictions on fields.

The following code defines the constructor of this class:

Public StringComponent ()

The constructor must have the same name as the class. It can be reloaded, but cannot return values. Therefore, it does not have a prefix of the returned value type. When you create a new class instance, the constructor will automatically execute it. At the same time, the garbage collection mechanism of C # begins to manage the instance, and resources will be reclaimed when appropriate.
Then, we have compiled a GetString () function, which returns the corresponding records based on the index value passed in by the user:

Public string GetString (int index)
{... Return StringsSet [index];}

Note the Exception Handling Methods:

Throw new IndexOutOfRangeException ();

As a robust component, the exception handling mechanism is indispensable. Although it may consume some resources, the security improvement that it brings will make you feel that the resources consumed are negligible. Here we use a system-defined exception class IndexOutOfRangeException (). In fact, more often, you must define your own exception classes to adapt to 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;
}
}

Defining an Exception class is no different from defining a common class. The only difference is that the Exception class must inherit from the System. Exception class. In fact, Microsoft recommends that you use all user-defined exception classes as subclasses of ApplicationException classes. Put the MyApplicationException class in the namespace CompCS, so that you can rewrite the Exception Handling Method in the GetString () function. The following is a GetString () method with a better Exception Handling Mechanism:

Public string GetString (int index) {try {if (index <0) | (index> = StringsSet. length) {throw new MyApplicationException ("parameter out of range") ;}} catch (MyApplicationException mErr) {Console. writeLine (mErr. AMsg);} catch (Exception Err) {Console. writeLine (Err. message );}
Return StringsSet [index];
}

In this way, you can cope with more complex situations.

Next, we will consider adding events to this class. The introduction of the event mechanism 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 an event. Put this definition in our class ComponentCS. in StringComponent, then we add a function Modify (), which modifies the value of the specified position in the character array StringsSet and raises the OnModify event. In the Modify event, we call the function specified by 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 use the following method to call:

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 the function DoIt (), we first establish a StringComponent Class Object mysc, and then associate its Mofidied event to the Called () method:

Mysc. Modified + = new EventHandler (Called );

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

Now we get a simple but 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 compile it into a. dll (Dynamic Link Library) file for release. The biggest benefit of publishing a. dll file is that the content in the. dll file has been compiled, which can greatly speed up the program running and protect the source code.

To compile the generated. cs file into a. dll file, follow these steps:

Csc.exe/t: library/debug +/out: myCom. dll example. cs

In this way, the. dll file named myCom. dll is output.

OK, we have completed a component. Although it is small, it is very complicated. This is the basis of all components, and the whole process will take less than 10 minutes.

Of course, if it is a component that has practical use value, we need to consider more than that, but we can see that C #'s powerful support for components can greatly improve our development efficiency, so that we can focus more on algorithm design and other aspects to develop better components.

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.