C # Determines whether a class has a "specified name" method

Source: Internet
Author: User

In C #, you can resolve this problem by reflection parsing the metadata, as shown in the following example code:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 usingSystem;usingSystem.Reflection;namespaceHello{    class Program    {        staticvoidMain(string[] args)        {            if(IsMethodDefined(typeof(Utils), "HelloWorld"))            {                Console.WriteLine("Utils类中有方法HelloWorld");            }            else            {                Console.WriteLine("Utils类中没有方法HelloWorld");            }            Console.ReadKey();        }                   /// <summary>        /// 判断一个类中有无"指定名称"的方法        /// </summary>        /// <param name="type"></param>        /// <param name="methodName"></param>        /// <returns></returns>        staticboolIsMethodDefined(Type type,stringmethodName)        {            boolresult = false;            foreach(MemberInfo m intype.GetMembers())            {                if(m.Name == methodName)                {                    result = true;                    break;                }            }            returnresult;        }    }    publicstaticclassUtils    {        publicstaticvoid HelloWorld()        {            Console.WriteLine("Hello World!");        }    }}

C # Determines whether a class has a "specified name" method

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.