[英]Get only the current class members via Reflection
Assume this chunk of code: 假设这段代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace TestFunctionality
{
class Program
{
static void Main(string[] args)
{
// System.Reflection.Assembly.GetExecutingAssembly().Location
Assembly assembly = Assembly.LoadFrom("c:\\testclass.dll");
AppDomain.CurrentDomain.Load(assembly.GetName());
var alltypes = assembly.GetTypes();
foreach (var t in alltypes)
{
Console.WriteLine(t.Name);
var methods = t.GetMethods(/*BindingFlags.DeclaredOnly*/);
foreach (var method in methods)
Console.WriteLine(
"\t--> "
+(method.IsPublic? "public ":"")
+ (method.IsPrivate ? "private" : "")
+ (method.IsStatic ? "static " : "")
+ method.ReturnType + " " + method.Name);
}
Console.ReadKey();
}
}
}
I am trying to get the definition of methods that are defined in this class but not from the base class. 我试图获得在此类中定义但不从基类定义的方法的定义。 ie, I don't want to get things like
也就是说,我不想得到类似的东西
System.String ToString() // A method in the base class object.
How can I filter them out? 我怎样才能过滤掉它们?
I tried to pass BindingFlags.DeclaredOnly
but that filters everything. 我试图通过
BindingFlags.DeclaredOnly
但过滤BindingFlags.DeclaredOnly
了所有内容。 This is inside testclass.dll : 这是在testclass.dll中 :
namespace TestClass
{
public class Class1
{
public static int StaticMember(int a) { return a; }
private void privateMember() { }
private static void privateStaticMember() { }
public void PublicMember() { }
public void PublicMember2(int a) { }
public int PublicMember(int a) { return a; }
}
}
What do you suggest? 你有什么建议?
Thank you. 谢谢。
You want this: 你要这个:
cl.GetMethods(BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Public);
Per the MSDN documentation it states that DeclaredOnly
: 根据MSDN文档,它声明了
DeclaredOnly
:
Specifies that only members declared at the level of the supplied type's hierarchy should be considered.
指定仅应考虑在提供的类型的层次结构级别声明的成员。 Inherited members are not considered.
不考虑继承的成员。
Now, maybe you explicitly want methods that aren't public
: 现在,也许您明确要求不
public
方法:
cl.GetMethods(BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.NonPublic);
If you want both public
and non- public
method, do this: 如果你想同时
public
和非public
的方法,这样做:
cl.GetMethods(BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic);
Notice that each query contains Instance
and Public
or NonPublic
, that's because the documentation states the following: 请注意,每个查询都包含
Instance
和Public
或NonPublic
,这是因为文档说明了以下内容:
You must specify Instance or Static along with Public or NonPublic or no members will be returned .
您必须与Public或NonPublic一起指定Instance或Static ,否则将不返回任何成员 。
我想你想要DeclaredOnly
绑定标志
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.