简体   繁体   English

在C#中使用methodinfo调用通用参数化方法

[英]call generic parameterized method using methodinfo in c#

I have one class which i try to create with the help of Avtivator.CreateInstance because i am getting the class name at run time as an string. 我有一个类,尝试在Avtivator.CreateInstance的帮助下创建,因为我在运行时将类名作为字符串获取。 So, in that class i have some method with one parameter of type List, now my question is how to call this type of method using MethodInfo. 因此,在该类中,我有一些方法具有一个类型为List的参数,现在我的问题是如何使用MethodInfo调用这种类型的方法。 eg 例如

Class XHospital{

    private string HospitalName;
    private IList<string> docList;
    public void SetDoctorList(List<string> docList){

        this.docList = docList;
       // some other code snippet here after getting docList
    }
    // .... rest of the code
}

Now creating Hospital class and calling method 现在创建医院类和调用方法

public void SetHospitalDetails(string hospitalName, string methodName){

    Type NewType = Type.GetType(hospitalName);
    Object NewClass = Activator.CreateInstance(NewClass, new object[]{});
    MethodInfo method = NewType.GetMethod(methodName);
    IList<string> docs = new List<string>(){ "doc1", "doc2" };
    method.Invoke(NewClass, new object[] { docs });//-------------  here i am 
       //  getting exception stating ...
       /*   Object of type 'System.Collections.Generic.List`1[System.Object]' 
            cannot be converted to type 
            'System.Collections.Generic.List`1[System.String]' */
}

Please help what i am doing wrong... Note: I am not allow to make any change in XHospital class. 请帮助我做错了事...注意:我不允许在XHospital类中进行任何更改。 So i can't handle it by myself.*** Thanks in advance. 因此,我无法自己处理。***预先感谢。

From documentation : 文档

An argument list for the invoked method or constructor. 被调用的方法或构造函数的参数列表。 This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked. 这是一个对象数组,其编号,顺序和类型与要调用的方法或构造函数的参数相同。

The fix is to NOT make your variable more abstract ( IList<String> ) if it is the exact concrete type ( List<String> ) you need to pass in. So try this instead: 解决的方法是,如果您要传递的正是确切的具体类型( List<String> ),则不要使变量更抽象( IList<String> )。因此,请尝试以下操作:

 List<string> docs = new List<string>(){ "doc1", "doc2" };
 method.Invoke(NewClass, new object[]{docs} );

Your code is right except: Object NewClass = Activator.CreateInstance(NewClass, new object[]{}); 您的代码是正确的,除了:Object NewClass = Activator.CreateInstance(NewClass,new object [] {}); It should be Object NewClass = Activator.CreateInstance(NewType, new object[]{}); 它应该是Object NewClass = Activator.CreateInstance(NewType,new object [] {});

It works well. 它运作良好。 If you still have problems, try set the field value directely. 如果仍然有问题,请尝试直接设置字段值。 field.SetValue(NewClass, anything); field.SetValue(NewClass,任何东西);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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