简体   繁体   中英

Reflection - Calling Method dynamically on specified Class Name

I need to use Reflection concept of Dot Net and I don't have much expertise on it. I will get class & method name as string and need to invoke that method on class.

Following is the class on which I need to invoke method:

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

Now in the following method, I will receive Parent Class Name, Sub Class Name and Method to be called.

Like following:

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

I tried a lot doing this but not able to do.

Any help would be greatly appreciated.

Thanks.

I assume that you know that the class will always be in the same assembly as PerformOperation. If it is not then you need the name of the assembly where it is located.

You don't need the ParentClass, but you do need the full name of the SubClass (including the namespace).

I assume that your class will always have a default constructor and that your method will never have any parameters.

If the above holds true, the following should work:

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);
}

Edit: added method to instantiate an object of a given class and returning the value of a given field on it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM