C # How do you solve a circular reference to an object

I came across what, in my opinion, could be a serious problem for my code, and I was hoping that someone here could explain to me how I would work on the problem.

I have 2 classes, each of which has the property of another class that creates a circular link. I plan to serialize these classes and use XSLT to format the output, but I assume that this will fail due to a circular reference.

Example

public class Book
{
  public BookShop TheShop = new BookShop();
}
public class BookShop
{
  list<Book> Books = new list<Book>();
}

So, from this example, every book will be in a bookstore, and in every bookstore there will be many books. If I serialize a bookstore, it then serializes each book, which then serializes the bookstore and so on round and round. How should I handle this?

+3
5
+6

[XmlIgnore] TheShop, .

.

+1

, BookShop (IBookShop), Book . BookShop Book:

public class Book
{
    public Book(IBookShop bookShop)
    {
        TheStop = bookShop;
    }
    [XmlIgnore]
    public IBookShop TheShop { get; set; }
}
public interface IBookShop 
{
    void SomeMethod();
}
public class BookShop : IBookShop
{
    list<Book> Books = new list<Book>();
    public void SomeMethod()
    {
    }
}
+1

System.Xml.Serialization.XmlSerializer, TheShop System.Xml.Serialization.XmlIgnoreAttribute:

public class Book
{
  [System.Xml.Serialization.XmlIgnore]
  public BookShop TheShop;
}

, , BookShop , . MSDN

0

, . , , , , . , ( , XML ​​ , , XML, , , , fooobar.com/questions/1012659/... ).

, , , , .

: ? , TheShop. , , .

- ( , uri) , , , memoise - TheShop , _theShop null, , _theShop . , .

, XSLT - ( XHTML - ), XML. , , XML, , , , . , ( deserialise XML), , , XML , . , , ToXml() WriteBookToXml() .

0
source

Source: https://habr.com/ru/post/1776716/


All Articles