2

我正在尝试通过 ac# forms 应用程序获取 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<>() 的调用中使用类型作为“classItem”。

我想整个方法是错误的,我很想得到一些建议。

4

3 回答 3

2

Your call to 'BindMethodNames' should use a type for the generic , not an instance, but you can't write code to do this without using reflection.

Then again, there is no point in using a generics here - wouldn't this work?

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); 
    } 
} 
于 2012-07-06T10:28:19.460 回答
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);
    }
}
于 2012-07-06T10:28:17.823 回答
0

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

var method = typeof(Foo).GetMethod("BindMethodNames", BindingFlags.Instance |
                                                      BindingFlags.NonPublic);
var generic = method.MakeGenericMethod(classItem);
generic.Invoke(this);
于 2012-07-06T10:26:15.803 回答