C# Don';t返回ToString,Equals,GetHashCode,GetType with Type.GetMethods()
考虑到一些类似的类:C# Don';t返回ToString,Equals,GetHashCode,GetType with Type.GetMethods(),c#,reflection,methods,C#,Reflection,Methods,考虑到一些类似的类: public class MyBaseClass() { public void MyMethodOne() { } public virtual void MyVirtualMethodOne() { } } public class MyMainClass : MyBaseClass() { public void MyMainClassMethod() { } public over
public class MyBaseClass()
{
public void MyMethodOne()
{
}
public virtual void MyVirtualMethodOne()
{
}
}
public class MyMainClass : MyBaseClass()
{
public void MyMainClassMethod()
{
}
public override void MyVirtualMethodOne()
{
}
}
如果我运行以下命令:
var myMethods= new MyMainClass().GetType().GetMethods();
我回来了:
- MyMethodOne
- MyVirtualMethodOne
- MyMainClassMethod
- 托斯特林
- 相等于
- GetHashCode
- GetType
myMethods
- 托斯特林
- 相等于
- GetHashCode
- GetType
var exceptonList = new[] { "ToString", "Equals", "GetHashCode", "GetType" };
var methods = myInstanceOfMyType.GetType().GetMethods()
.Select(x => x.Name)
.Except(exceptonList);
试试这个
GetMethods().Where((mi)=> mi.DeclaringType != typeof(object));
使用一点LINQ,就可以消除对象
类中声明的所有方法。如果使用
var myMethods = new MyMainClass().GetType().GetMethods()
.Where(m => m.DeclaringType != typeof(object));
您将放弃那些最底层的四种方法,除非它们在您的继承权中被覆盖
(我自己也想要这种行为,但如果你想排除这四种行为,那么Cuong的回答就可以了。)你也可以这样做:
var methods = typeof(MyMainClass)
.GetMethods()
.Where(m => !typeof(object)
.GetMethods()
.Select(me => me.Name)
.Contains(m.Name));
我们也可以明确地排除它们:
public static IEnumerable<MethodInfo> GetMethodsWithoutStandard(this Type t)
{
var std = new List<string>() { nameof(ToString),
nameof(Equals),
nameof(GetHashCode),
nameof(GetType)};
return t.GetMethods().Where(x => !std.Contains(x.Name));
}
公共静态IEnumerable GetMethodsWithoutStandard(此类型为t)
{
var std=new List(){nameof(ToString),
名称(等于),
名称(GetHashCode),
nameof(GetType)};
返回t.GetMethods(),其中(x=>!std.Contains(x.Name));
}
这种方法并不害怕覆盖这些方法您可以使用这些方法只获取
MyMainClassMethod
和MyVirtualMethodOne
,但我认为“声明的方法包括但不包括对象
中的方法”没有相应的标志。这不是他想要的-这将只提供三种方法中的两种。是的,您需要使用BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly
。(前三个是GetMethods()
重载使用的标志。)GetMethods()。其中((mi)=>mi.DeclaringType!=typeof(object))现在呢?是的,现在你已经接受了我的答案:)对不起,伙计。。我后来注意到你的回答。。。我想你的答案更完整了..投票赞成退回,但在这种情况下,我想把它们全部排除在外