2

我已经阅读了两天的反射示例,但我似乎无法将所有内容拼凑起来以满足我的需要。事实上,我以为我在使用反射,直到我注意到我的“使用 System.Reflection”是灰色的。:-)

我有一个 xml 文件,其中包含我的类名和其中包含的方法。方法的顺序甚至名称都可以更改。一旦我读到它们,我希望能够执行它们。看起来很简单。

我有以下测试代码:

    // myClassName = "namespace.TransactionServices"
    Type tb = Type.GetType(myClassName);

    // Classes will always have the same constructor
    object classInstance = Activator.CreateInstance (
        tb, 
        new object[] 
        {
            authorization.apiKey, 
            authorization.userName, 
            testData.servicesEndPoint
        });

    //Grab the method I want

    //myMethodName = "GetVersion"
    MethodInfo mymethod = tb.GetMethod(myMethodName);
    // no parameters for this method call
    object result = mymethod.Invoke(classInstance, null);

tb 为空。我只是想努力获得正确的 API 来创建类,但我什至不知道我所拥有的其余部分是否有效。

有什么建议么?

谢谢

编辑:添加命名空间。Activator.CreateInstance 正在返回找不到构造函数的错误。它就在那里。

4

3 回答 3

3

类名必须是完全限定的(包括命名空间,并且很可能是程序集)才能被解析。如果您知道该类在当前正在执行的程序集中,则可以使用Assembly.GetExecutingAssembly() .GetType()

于 2011-04-05T18:51:15.670 回答
2

你确定你指定了完整的类名,包括命名空间吗?没有命名空间,结果将为空。

于 2011-04-05T18:50:29.987 回答
0

对于 GetType,您必须提供一个完全限定的名称。您可以使用现有对象获取它

MyObject.GetType().AssemblyQualifiedName;
于 2011-04-05T18:53:48.700 回答