获取所有类中的所有方法名称

时间:2012-07-06 10:23:24

标签: c# reflection method-names

我正在尝试通过c#表单应用程序获取vb.net项目中所有类的所有方法名称。

我到目前为止:

private void BindMethods()
{
    var assembly = typeof(VBProject.Class1).Assembly;
    var publicClasses = assembly.GetExportedTypes().Where(p => p.IsClass);

    foreach (var classItem in publicClasses)
    {
        BindMethodNames<classItem>();
    }
}

private void BindMethodNames<T>()
{
    MethodInfo[] methodInfos = typeof(T).GetMethods(BindingFlags.Public | BindingFlags.Static);

    Array.Sort(methodInfos,
        delegate(MethodInfo methodInfo1, MethodInfo methodInfo2)
        {
            return methodInfo1.Name.CompareTo(methodInfo2.Name)
        });

    foreach (var methodInfo in methodInfos)
    {
        this.comboMethods.Items.Add(methodInfo.Name);
    }
}

现在问题是,(因为我做错了)它不允许我在BindMethodNames&lt;&gt;()的调用中使用类型“classItem”。

我猜整个方法都错了,我很想得到一些建议。

3 个答案:

答案 0 :(得分:2)

您对'BindMethodNames'的调用应该使用泛型的类型,而不是实例,但是如果不使用反射,则无法编写代码来执行此操作。

然后,在这里使用泛型是没有意义的 - 这不会起作用吗?

private void BindMethods() 
{ 
    var assembly = typeof(VBProject.Class1).Assembly; 
    var publicClasses = assembly.GetExportedTypes().Where(p => p.IsClass); 

    foreach (var classItem in publicClasses) 
    { 
        BindMethodNames(classItem); 
    } 
} 

private void BindMethodNames(Type type) 
{ 
    MethodInfo[] methodInfos = type.GetMethods(BindingFlags.Public | BindingFlags.Static); 

    Array.Sort(methodInfos, 
        delegate(MethodInfo methodInfo1, MethodInfo methodInfo2) 
        { 
            return methodInfo1.Name.CompareTo(methodInfo2.Name) 
        }); 

    foreach (var methodInfo in methodInfos) 
    { 
        this.comboMethods.Items.Add(methodInfo.Name); 
    } 
} 

答案 1 :(得分:1)

针对这种情况的泛型并不是特别有用。您已经在迭代从所选程序集中检索到的Type个实例的列表,因此您的第二个方法只需要将目标类型作为参数接收。

private void BindMethodNames(Type target)
{
    MethodInfo[] methodInfos = target.GetMethods(
        BindingFlags.Public | BindingFlags.Static);

    Array.Sort(methodInfos,
        delegate(MethodInfo methodInfo1, MethodInfo methodInfo2)
        {
            return methodInfo1.Name.CompareTo(methodInfo2.Name);
        });

    foreach (var methodInfo in methodInfos)
    {
        this.comboMethods.Items.Add(methodInfo.Name);
    }
}

答案 2 :(得分:0)

您需要使用反射调用该方法:

var method = typeof(Foo).GetMethod("BindMethodNames", BindingFlags.Instance |
                                                      BindingFlags.NonPublic);
var generic = method.MakeGenericMethod(classItem);
generic.Invoke(this);
相关问题