1

我需要使用 Dot Net 的反射概念,我对此没有太多的专业知识。我将类和方法名称作为字符串获取,并且需要在类上调用该方法。

以下是我需要调用方法的类:

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"
}

我尝试了很多这样做但无法做到。

任何帮助将不胜感激。

谢谢。

4

1 回答 1

2

我假设您知道该类将始终与 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);
}

编辑:添加方法来实例化给定类的对象并返回给定字段的值

于 2013-03-13T08:31:24.673 回答