[英]How to remove variable of Specific Type from Object[] in C#
I have an array of Objects
type which have information of variable of different classes, say, ClassA
and ClassB
. 我有一个Objects
类型的数组 ,其中包含不同类的变量信息,例如ClassA
和ClassB
。
public object[] SelectedObjects { get; }
Now I am filtering the objects of ClassB
which I need to remove from the array of SelectedObjects
. 现在,我正在过滤需要从SelectedObjects
数组中删除的ClassB
对象。
var selectedClassBObjects = SelectedObjects.OfType<ClassB>().ToList();
When I perform the operation of Remove()
or RemoveAll()
, it does not do anything . 当我执行Remove()
或RemoveAll()
,它不会执行任何操作 。
Can anyone suggest me how to perform this operation? 谁能建议我如何执行此操作?
I need to remove objects of ClassB
because at a time only one object of ClassB
can be present when user is trying to Highlight the objects on the canvas. 我需要删除ClassB
对象,因为当用户尝试突出显示画布上的对象时,一次只能显示ClassB
一个对象。 First remove the ClassB
objects then add the newly selected ClassB
objects to SelectedObjects[]
. 首先删除ClassB
对象,然后将新选择的ClassB
对象添加到SelectedObjects[]
。
You can't remove anything from an array, you will need to create a new one. 您无法从数组中删除任何内容,需要创建一个新数组。 If you want to exclude objects of type ClassB
you can do: 如果要排除ClassB
类型的对象,则可以执行以下操作:
SelectedObjects = SelectedObjects.Where(x => !(x is ClassB)).ToArray();
If you want a modifiable collection, List<T>
is a better choice than an array. 如果需要可修改的集合,则List<T>
比数组是更好的选择。
If you insist on array you can put the backing field explicitly: 如果您坚持使用数组 ,则可以明确地放置支持字段 :
private object[] m_SelectedObjects = new object[0];
public object[] SelectedObjects {
get {
return m_SelectedObjects;
}
}
private void MyRemove() {
// We can't modify read-only property but can operate with its backing field
m_SelectedObjects = m_SelectedObjects?.OfType<ClassB>()?.ToArray();
}
Another possibility is to change array object[]
into List<object>
: 另一种可能性是将数组 object[]
更改为List<object>
:
public List<object> SelectedObjects { get; }
...
// We still can't assign SelectedObjects but we can modify the collection now
SelectedObjects?.RemoveAll(item => !(item is TypeB));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.