C# 获取所有类中的所有方法名称
我试图通过一个c#forms应用程序获取vb.net项目中所有类中的所有方法名 我走了这么远:C# 获取所有类中的所有方法名称,c#,reflection,method-names,C#,Reflection,Method Names,我试图通过一个c#forms应用程序获取vb.net项目中所有类中的所有方法名 我走了这么远: private void BindMethods() { var assembly = typeof(VBProject.Class1).Assembly; var publicClasses = assembly.GetExportedTypes().Where(p => p.IsClass); foreach (var classItem in publicClas
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);
}
}
private void BindMethods()
{
var assembly=typeof(VBProject.Class1).assembly;
var publicClasses=assembly.GetExportedTypes()。其中(p=>p.IsClass);
foreach(PublicClass中的var classItem)
{
BindMethodNames();
}
}
私有void BindMethodNames()
{
MethodInfo[]methodInfos=typeof(T).GetMethods(BindingFlags.Public | BindingFlags.Static);
Array.Sort(methodInfos,
代理(MethodInfo methodInfo1、MethodInfo methodInfo2)
{
返回methodInfo1.Name.CompareTo(methodInfo2.Name)
});
foreach(methodInfo中的var methodInfo)
{
this.comboMethods.Items.Add(methodInfo.Name);
}
}
现在的问题是,(因为我做错了什么),它不允许我在调用BindMethodNames()时使用类型作为“classItem”
我想整个方法都是错误的,我很想得到一些建议。您需要调用带有反射的方法:
var method = typeof(Foo).GetMethod("BindMethodNames", BindingFlags.Instance |
BindingFlags.NonPublic);
var generic = method.MakeGenericMethod(classItem);
generic.Invoke(this);
对于这种情况,泛型没有特别的帮助。您已经在迭代从所选程序集检索的
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);
}
}
对“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);
}
}
谢谢你的快速回复谢谢你的快速回复