简体   繁体   English

从该对象中分配一个对象C#

[英]Assign an object from within that object C#

I was curious to know if there was an easy way to do the following. 我很想知道是否有一种简单的方法来执行以下操作。

public class Person
{
    public String Name{ get; set; }

    public void Load(Stream stream)
    {
        this = new XmlSerializer(GetType()).Deserialize(stream) as Person;
    }

    public void Save(Stream stream)
    {
        new XmlSerializer(GetType()).Serialize(stream, this);
    }
}

I realize that this will not compile; 我意识到这将无法编译; however, I find that sometimes I wish to assign an object from within itself. 但是,我发现有时我希望从自身内部分配一个对象。 (ie the object undergoes a massive change and I wish to instead of changing each value, simply "reset" the object by calling its constructor and setting the object to its new version). (即对象发生了巨大的变化,我希望不更改每个值,而只是通过调用其构造函数并将其设置为新版本来“重置”该对象)。

Any thoughts on how to do this? 有关如何执行此操作的任何想法?

You could do this with Automapper that would just copy the contents of an instance into your instance: 您可以使用Automapper做到这一点,该方法只会将实例的内容复制到您的实例中:

public void Load(Stream stream)
{
    Mapper.DynamicMap( new XmlSerializer(GetType()).Deserialize(stream) as Person, this );
}

Nevertheless, I would prefer 不过,我宁愿

public static Person Load(Stream stream)
{
    return new XmlSerializer(GetType()).Deserialize(stream) as Person;
}

so that instead of overwriting the contents, you return a new instance and could just switch references in the client code. 因此,您无需覆盖内容,而是返回一个新实例,并且只需切换客户端代码中的引用即可。

Just use a static method that returns a new instance: 只需使用返回新实例的静态方法即可:

public class Person
{
    public String Name { get; set; }

    public static Person Load(Stream stream)
    {
        return new XmlSerializer(GetType()).Deserialize(stream) as Person;
    }
}

Call it like this: 这样称呼它:

var person = Person.Load(someStream);

Edit: I didn't notice your requirement that this is in an interface implementation. 编辑:我没有注意到您的要求,这是在接口实现中。 If possible, you may want to refactor the design. 如果可能,您可能需要重构设计。 If you can't and your object is simple enough, you could instantiate a new object and copy the members over: 如果不能,并且对象足够简单,则可以实例化一个新对象并将成员复制到以下位置:

public void Load(Stream stream)
{
    Person p = new XmlSerializer(GetType()).Deserialize(stream) as Person;
    // todo: copy properties from p to this:
    // this.Name = p.Name;
    // etc
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM