简体   繁体   English

如何从一个对象(另一个对象的副本)中删除多个项目,而又不影响其中一个派生对象?

[英]How can I delete several items from an object, which is copy of another object, without affecting the one of which is derived?

help me please to use the function "RemoveAll" or maybe there should be another implementation. 请帮我使用功能“ RemoveAll”,否则可能应该有另一个实现。 I have an object ( services ) which contains a list with items. 我有一个对象( 服务 ),其中包含带有项目的列表。 I make another object ( anotherService ) which is equal with the first. 我创建另一个对象( anotherService ),该对象与第一个对象相等。

I should remove from second object ( anotherService ) items which have mainService == false. 我应该从第二个对象( anotherService )中删除具有mainService == false的项目。

I use the "RemoveAll" function, but after this action is made, from the object ( services ) items which are mainService = false are also removed. 我使用“ RemoveAll”功能,但是在执行此操作后,还将从对象( 服务 )中删除mainService = false的项目。 I need to have the first object completed how it was before removing. 我需要先删除第一个对象,然后再完成操作。

var services = DictionaryObject.GetDictionaryValidatedByDate<ServiceInfo>(DictionaryType.REF_SERVICE, DateTime.Now);

var anotherService = services;

anotherService.RemoveAll(p =>                
    {                   
        if (p.Model.mainService == false)
        {
           return true;
        }
        return false;
    });

Thank you all. 谢谢你们。

The line: 该行:

var anotherService = services;

simply defines a new variable and assigns the existing value (almost certainly a class reference) to that variable; 只需定义一个新变量并将现有值(几乎可以肯定是类引用)分配给该变量; no new object is created. 没有创建新对象。 Any member-access on a reference is going to go to the same actual object, no matter which variable you use (there is only one object). 无论您使用哪个变量(只有一个对象),对引用的任何成员访问都将转到相同的实际对象。

To do what you need, you would need to create a shallow or deep clone (depending on what exactly you want to happen). 要做到你需要什么,你需要(这依赖你想发生什么)创建一个浅或深克隆。

A shallow clone is pretty easy to do by manually adding a Clone() method or similar (maybe ICloneable ) which copies the properties (noting that in the case of lists, a new list with the same data is usually created). 通过手动添加Clone()属性的Clone()方法或类似方法(可能是ICloneable ),浅克隆很容易实现(请注意,在使用列表的情况下,通常会创建具有相同数据的列表)。 A deep clone is trickier - a common cheat there is to serialize and deserialize the item. 深度克隆比较棘手-序列化和反序列化项是一个常见的作弊行为。

The Serialization approach can be found here in this answer : 可以在此答案中找到序列化方法:

For reference I have posted it here. 供参考,我已经在这里发布了。

public static T DeepClone<T>(T obj)
{
 using (var ms = new MemoryStream())
 {
   var formatter = new BinaryFormatter();
   formatter.Serialize(ms, obj);
   ms.Position = 0;

   return (T) formatter.Deserialize(ms);
 }
}

Your problem is that you are changing the same object, just through a different reference. 您的问题是您只是通过不同的引用来更改同一对象。 you need to make sure that you removes items from a different object, which contains copies of the same information. 您需要确保从另一个对象中删除项目,该对象包含相同信息的副本。 There are a few ways you could do this. 有几种方法可以做到这一点。 The simplest is to just create 2 objects: 最简单的是只创建2个对象:

var services = DictionaryObject.GetDictionaryValidatedByDate<ServiceInfo>(DictionaryType.REF_SERVICE, DateTime.Now);

var anotherService =  DictionaryObject.GetDictionaryValidatedByDate<ServiceInfo>(DictionaryType.REF_SERVICE, DateTime.Now);;

anotherService.RemoveAll(p =>                
    {                   
        if (p.Model.mainService == false || p.Model.mainService == true)
        {
           return true;
        }
        return false;
    });

or you could copy/clone your object something like: 或者您可以复制/克隆对象,例如:

var anotherService = services.Copy(); //or maybe use a copy constructor here instead:
//  var anotherService = new ServiceInfo(sevices);
anotherService.RemoveAll(p =>                
{                   
    if (p.Model.mainService == false || p.Model.mainService == true)
    {
       return true;
    }
    return false;
});

When you implement the Copy() method or the constructor which takes the object to copy you need to make sure that you create copies of dictionaries and do not just use references to the same dictionary. 当实现Copy()方法或将对象复制的构造函数时,您需要确保创建字典的副本,而不仅仅是使用对同一字典的引用。

if your object being returned is just an IDictionary<K,V> (its not clear from the code provided) you may be able to do this: 如果返回的对象只是一个IDictionary<K,V> (从提供的代码中不清楚),则可以执行以下操作:

var anotherService = new Dictionary<KeyType,ValueType>(services)
anotherService.RemoveAll(p =>                
{                   
    if (p.Model.mainService == false || p.Model.mainService == true)
    {
       return true;
    }
    return false;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何制作从List派生的对象的深层副本<T> - How to make a deep copy of an object which is derived from a List<T> 我怎么知道一个对象是否来自特定的类 - How can I tell if one object is derived from a particular class 确定从哪个泛型类型对象派生 - Determine which genric type object is derived from 如何在我的派生类型中使用基类型的方法,这些方法返回基类型的 object? - How can I use a base type's methods, which return an object of the base type, in my derived type? 如何将派生的 object 添加到从同一接口继承但使用 generics 的对象集合中? - How do I add a derived object to a collection of objects which inherit from the same interface, but use generics? 如何将一种对象类型的对象深复制到共享继承结构的另一种对象类型 - How can I deep copy an object of one object type to another object type that share an inheritance structure 如何将Base对象的引用更改为Derived,并将其作为Derived类型进行实例化 - How to change reference of Base object to Derived which was instatiated as Derived type 当它可以是多种类型时,如何在不将其转换为一种类型的情况下访问“对象”的特定字段? - How do I access a certain field of 'object' without casting it to one type when it can be several types? 修改字典中的项目而不影响原始对象 - Modifying items in dictionary without affecting the original object 如何将一个列表复制到另一个具有 object 和 C# 附加属性的列表? (没有foreach) - How do I copy one list to another that has an object with additional properties in C# ? (without a foreach)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM