How to Use reflection to implement the following generic method call?

Source: Internet
Author: User

 

1.Code

 

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

Using System. Reflection;

Namespace GenericReflectingApp1

{

Class Program

{

Static void Main (string [] args)

{

MyGeneric <string> myString = new myGeneric <string> ();

 

MyString. Show <int> (100 );

 

ShowTypeInfo (myString. GetType ());

 

// An error occurs. "An ambiguous match is found. ",

// MethodInfo myMethod = myString. GetType (). GetMethod ("Show ");

 

// How to specify generic method parameters

// MethodInfo myMethod = myString. GetType (). GetMethod ("Show", new Type [] {});

 

// Console. WriteLine (string. Format ("Is Generic Method: {0}", myMethod. IsGenericMethod. ToString ()));

Console. Read ();

}

 

Static void ShowTypeInfo (Type t)

{

Console. WriteLine (string. Format ("TypeName: {0} Method List:", t. Name ));

 

Foreach (MethodInfo obj in t. GetMethods ())

{

 

Console. WriteLine (string. Format ("Method Name: {0}; IsGeneric Method: {1}; ContainsGenericParameters: {2 }",

Obj. Name, obj. IsGenericMethod. ToString (), obj. ContainsGenericParameters. ToString ()));

 

If (obj. GetGenericArguments (). Count ()> 0)

{

Console. WriteLine (string. Format ("Generic Arguments's count: {0}", obj. GetGenericArguments () [0]. Name

));

}

}

}

}

 

Class myGeneric <T>

{

Public void Show <U> (U u)

{

Console. WriteLine (u. ToString ());

}

 

Public void Show (T t)

{

Console. WriteLine (t. ToString ());

}

}

}

 

 

2. How to Find the generic method Show <U> (U u) MethodInfo through reflection.

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.