[英]Reflection - Calling Method dynamically on specified Class Name
我需要使用Dot Net的Reflection概念,但是我对此没有太多专业知识。 我将以字符串形式获取类和方法的名称,并需要在类上调用该方法。
以下是我需要在其上调用方法的类:
namespace ObjectRepositories
{
class Page_MercuryHome : CUITe_BrowserWindow
{
public new string sWindowTitle = "";
public Page_MercuryHome()
{
#region Search Criteria
this.SearchProperties[UITestControl.PropertyNames.Name] = "Blank Page";
this.SearchProperties[UITestControl.PropertyNames.ClassName] = "IEFrame";
this.WindowTitles.Add("Blank Page");
this.WindowTitles.Add("Welcome: Mercury Tours");
#endregion
}
public CUITe_HtmlEdit UIEdit_UserName = new CUITe_HtmlEdit("Name=userName");
public CUITe_HtmlEdit UIEdit_Password = new CUITe_HtmlEdit("Name=password");
public CUITe_HtmlInputButton UIInputButton_Login = new CUITe_HtmlInputButton("Name=login");
}
}
现在,在以下方法中,我将收到父类名称,子类名称和要调用的方法。
如下所示:
void PerformOperation(string ParentClass, string SubClass, string MethodName)
{
/* Suppose if I receive arguments as "Page_MercuryHome","CUITe_BrowserWindow","SetText")
then it should call SetText() method of subclass CUITe_BrowserWindow which is having Page_MercuryHome as Parent Class"
}
我做了很多尝试,但没有做到。
任何帮助将不胜感激。
谢谢。
我假设您知道该类将始终与PerformOperation在同一程序集中。 如果不是,则需要它所在的程序集的名称。
您不需要ParentClass,但确实需要SubClass的全名(包括名称空间)。
我假设您的类将始终具有默认的构造函数,并且您的方法将永远不具有任何参数。
如果上述情况成立,则应进行以下操作:
void PerformOperation(string fullClassName, string methodName)
{
ObjectHandle handle = Activator.CreateInstance(null, fullClassName);
Object p = handle.Unwrap();
Type t = p.GetType();
MethodInfo method = t.GetMethod(methodName);
method.Invoke(p, null);
}
object ReadField(string fullClassName, string fieldName)
{
ObjectHandle handle = Activator.CreateInstance(null, fullClassName);
Object p = handle.Unwrap();
Type t = p.GetType();
FieldInfo field = t.GetField(fieldName);
return field.GetValue(p);
}
编辑:添加的方法实例化给定类的对象并在其上返回给定字段的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.