gpt4 book ai didi

c# - IList 似乎不包含方法 "Remove"

转载 作者:行者123 更新时间:2023-11-30 22:26:40 24 4
gpt4 key购买 nike

我有一个 MyClass 实例,定义为:

public partial class MyClass  
{
public virtual string PropertyName1 { get; set; }
public virtual IList<Class2List> Class2Lists{ get; set; }
}

我使用反射尝试找到 Remove 方法:

object obj1 = myClassObject;
Type type = obj1.GetType();
Type typeSub = type.GetProperty("Class2Lists").PropertyType;

//this method can not find
MethodInfo methodRemove = typeSub.GetMethod("Remove");

// this method can find
MethodInfo methodRemove = typeSub.GetMethod("RemoveAt");

// there is no "Remove" method in the list
MethodInfo[] methodRemove = typeSub.GetMethods();

但是我找不到Remove方法,为什么?

最佳答案

  • IList<T>定义 RemoveAt() , 但它没有定义 Remove() .

  • IList<T>继承自 ICollection<T> ,它定义了 Remove() .

如何检索正确的 MethodInfo 的示例:

Type typeWithRemove = typeSub.GetInterfaces ()
.Where ( i => i.GetMethod ( "Remove" ) != null )
.FirstOrDefault ();

if ( typeWithRemove != null )
{
MethodInfo methodRemove = typeWithRemove.GetMethod ( "Remove" );
}

关于c# - IList<T> 似乎不包含方法 "Remove",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11663556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com