如何判断一个对象是否具有某个方法
例如:Form frm = new Form();
判断 Form 是否有load()方法
就是我new一个对象之后,判断这个对象是否具有load()方法
[解决办法]
考虑判断类Form是否有load方法吧;不要去判断实例
利用反射去处理
[解决办法]
简单的话,写"frm.",然后看.net有没有提示load()这个方法.
不过这种情况容易有误差.
如果想判断的话,在代码里面写"frm.load()",然后编译,看是否出错咯.
不知会不会理解错楼主的原意?
[解决办法]
public class Class1{ public Class1( ) { } public string Method1( ) { return " word"; } public string Method2( string strName ) { return strName; } }public class Class2{ public Class2( ) { } public bool FindMethod( string className , string methodName , Type[ ] paramType) { Type type = Type.GetType( className , true , true ); object dObj = Activator.CreateInstance( type ); MethodInfo method; if( paramType!= null ) method = type.GetMethod( methodName , paramType); else method = type.GetMethod( methodName , new Type[0] ); return method != null; }}//调用:Response.Write( new Class2( ).FindMethod( "Class1" , "Method1" , null );Response.Write( new Class2( ).FindMethod( "Class1" , "Method2" , new Type[ ] { typeof( string ) } ) );
[解决办法]
写了代码,但是没发现Form_Load呢!
其他的方法基本上都得到了;
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Reflection;namespace WindowsApplication3{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Type t = typeof(Form1); MethodInfo[] info = t.GetMethods(); foreach (MethodInfo i in info) { if (i.Name.ToLower().IndexOf("load") > -1) { MessageBox.Show(i.Name); } } } }}