. NET generic 02, generic usage,. net02

Source: Internet
Author: User

. NET generic 02, generic usage,. net02

In ". NET generic 01, why do you need generic and generic basic syntax", I learned about the basic concepts of generic. This article focuses on the use of generic. It mainly includes:

 

■ Notes for overload of generic methods
■ Generic type inference
■ Generic methods can also be constrained.
■ Generic interface
■ Generic delegation
■ Event generics using EventHandler <TEventArgs>

 

Notes for overload of generic methods

public class MyArray<T>{    public T myData;    public MyArray()    {        myData = default(T);    }    public void ShowInfo()    {        Console.WriteLine(myData.ToString());    }    public void ShowInfo(string str)    {        Console.WriteLine(str);    }    public void ShowInfo<T>(T data)    {        Console.WriteLine(data.ToString());    }}

The above description: generic methods can be used as method overloading.

 

It can be called in this way.

MyArray<Student> myArray = new MyArray<Student>();myArray.ShowInfo<CollegeStudent>(new CollegeStudent());myArray.ShowInfo<string>("HelloWorld");

 

However, there is another case: Two overloaded methods with unknown semantics are passed during compilation, but will not pass the call. For example:

public class MyArray<T>{    public void ShowInfo<TA, TB>(TA a, TB b){};    public void ShowInfo<TB, TA>(TA a, TB b){};}

 

If you call this method in this way, there will be a problem:

MyArray<Student> myArray = new MyArray<Student>();myArray.showInfo<Student, Student>(new Student(), new Student());

Therefore, for generic overload methods, you must note that the semantics is unknown.

 

Generic Type Inference

The compiler can infer which overload method is used based on the type of the method parameter. The general overload method is called first, and then the generic overload method is called.

MyArray. showInfo ("hello"); will call the ShowInfo (string str) overload method myArray. showInfo (new CollegeStudent (); The ShowInfo <T> (T data) overload method is called.

 

Generic methods can also be constrained.

We know that generic classes can have constraints, and so can generic methods.

public void ShowInfo<T>(T data)  where TData : Student{    Console.WriteLine(data.ToString());}

 

Generic Interface

. NET collection class provides multiple generic interfaces, such as: IList <T>, ICollection <T>, IComparable <>, IComparer <T>, IEnumerable <T>, IEnumerator <T>, IDictionary <TKey, TValue>, and so on.

When creating a custom class, you sometimes need to make the custom class implement a generic interface that specifies a specific type:

class MyClass<T> : IComparable<Int32>, IComparable<String>

 

Generic Delegation

Public class Generic Delegate {// declare the Generic delegate public Delegate string MyGenericDelegate <T> (T t); public static string GetPoint (Point p) {return stirng. format ("address is {0}, {1}", p. x, p. y);} public static string GetMsg (string str) {return str ;}} public static void Main () {MyGenericDelegate <string> myStrDel = new MyGenericDelegate <string> (GetMsg ); console. writeLine (myStrDel ("hello"); MyGenericDelegate <Point> myPointDel = new MyGenericDelegate <Point> (GetPoint); Console. writeLine (myPointDel (new Point (100,200 )));}

 

Use EventHandler <TEventArgs> event generic

Its complete definition is:

public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e) where TEventArgs: EventArgs

 

Assume there is a MessageReceiver class. When a connection is established, the OnConnected event is triggered and the message received is the OnMessageReceived event.

 

Before creating the MessageReceiver class, we must first customize a class derived from EventArgs and related to MessageReceiver.

public sealed class MessageReceivedEventArgs : EventArgs{    public string Message {get;set;}    public MessageReceivedEventArgs(string msg)    {        this.Message = msg;    }}

 

The MessageReceiver class contains two events: OnConnected and OnMessageReceived.

public class MessageReceiver{    public event EventHandler OnConnected;    public event EventHandler<MessageReceivedEventArgs> OnMessageReceived;    ...    public void DoSth()    {        if(OnMessageReceived != null)        {            OnMessageReceived(this, new MessageReceivedEventArgs(msg));        }    }}

The preceding Code uses if (OnMessageReceived! = Null) This judgment ensures that the event is not triggered when no subscriber registers for the event. However, in multi-threaded scenarios, this is not the most reasonable:

 

Assume that thread A registers an event as the subscriber and is preparing to trigger the event. Thread B also serves as the subscriber and cancels the event at the moment, that is, OnMessageReceived is changed to null, this makes thread A unable to trigger the event.

 

The solution is to assign the event variable to a local variable:

public class MessageReceiver{    public event EventHandler OnConnected;    public event EventHandler<MessageReceivedEventArgs> OnMessageReceived;    ...    public void DoSth()    {        var handler = OnMessageReceived;        if(handler != null)        {            handler(this, new MessageReceivedEventArgs(msg));        }    }}

In this way, when thread A registers as A subscriber and prepares to trigger an event, thread B deregister the registration at the moment in time, so that OnMessageReceived is null because OnMessageReceived has been assigned A value to the local variable handler, thread A can still trigger events.

 

References:
NET (version 2nd), Author: Wang Tao.

 

". NET generic" series include:

. NET generic type 01. Why do I need generic, basic generic syntax. NET generic type 02, and generic usage?
C # How to use generic classes, generic interfaces, generic methods, and generic delegation

Generics are designed to solve abstract problems. For example, the signatures of method A (int, int, string); B (string, char, char); C (int, float, char); are different, but do the same operation. We can see that they have one thing in common-three parameters. So I can define a generic method string functionWithThreeArg <T1, T2, T3> (T1 arg1, T2 arg2, T3 arg3)
Where... // generic constraints are implemented here. For example, the '+' operator is implemented.
{
String result = arg1 + arg2 + arg3;
Return result;
}
Now we can use the generic method to call a, B, and C.
A: functionWithThreeArg <int, int, string> (1, 2, "3 ");
B: functionWithThreeArg <string, char, char> ("1", 'B', 'C ');
C: functionWithThreeArg <int, float, char> (1, "1.5", 'A ');

Well, here is a simple explanation of the problem, not the actual code.

C # Generic usage

C # Generic
Generic is a new function in the C # language and Common Language Runtime Library (CLR) of version 2.0. Generics introduce the concept of type parameters. NET Framework, type parameters make it possible to design the following classes and Methods: these classes and Methods delay one or more types until the client Code declares and instantiate the class or method. For example, by using the generic type parameter T, you can write a single class that can be used by other client code without introducing the cost or risk of force conversion or packing during runtime, as shown below: // Declare the generic classpublic class GenericList <T> {void Add (T input) {}} class TestGenericList {private class ExampleClass {} static void Main () {// Declare a list of type intGenericList <int> list1 = new GenericList <int> (); // Declare a list of type stringGenericList <string> list2 = new GenericList <string> (); // Declare a list of ty Pe ExampleClassGenericList <ExampleClass> list3 = new GenericList <ExampleClass> () ;}use generic types to maximize code reuse, protect type security, and improve performance. The most common use of generics is to create a collection class .. The. NET Framework class library contains several new Generic collection classes in the System. Collections. Generic namespace. Use these classes as much as possible to replace common classes, such as the ArrayList in the System. Collections namespace. You can create your own generic interfaces, generic classes, generic methods, generic events, and generic delegation. You can restrict generic classes to access specific data types. Information about types used in generic data types can be obtained through reflection at runtime.
Refer to Baidu encyclopedia
 

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.