为什么我们需要阻止循环对象引用

时间:2021-07-01 19:44:16

I'm new to this. Can you please explain to me why the "Circular REference" is a bad thing, what's the bad result it may bring about?

我是新手。你能否向我解释为什么“循环引用”是一件坏事,它可能带来什么不好的结果?

1 个解决方案

#1


If you would serialize this into JSON then you would get an infinite JSON-document because at the time the Serializer serializes the CTest object into JSON and he reaches the Other property this property is referenced by itself and the serializer starts with serializing this object. And so one.

如果您将其序列化为JSON,那么您将获得无限的JSON文档,因为当Serializer将CTest对象序列化为JSON并且他到达Other属性时,该属性将被自身引用,并且序列化程序以序列化此对象开始。一个人。

public class CTest
{
    public CTest Other { get; set; }
    public string Description { get; set; }
}

[Test]
public void Circulartest()
{
    CTest instance = new CTest();
    instance.Description = "Hello";
    instance.Other = instance;

    JsonConvert.SerializeObject(instance);
}

This would result in following JSON file

这将导致以下JSON文件

{
    "Description": "Hello"
    "Other":
    {
        "Description": "Hello"
        "Other":
        {
            "Description": "Hello"
            "Other":
            {
                "Description": "Hello"
                "Other":
                {
                    ....never ending story
                }
            }
        }
    }
}

#1


If you would serialize this into JSON then you would get an infinite JSON-document because at the time the Serializer serializes the CTest object into JSON and he reaches the Other property this property is referenced by itself and the serializer starts with serializing this object. And so one.

如果您将其序列化为JSON,那么您将获得无限的JSON文档,因为当Serializer将CTest对象序列化为JSON并且他到达Other属性时,该属性将被自身引用,并且序列化程序以序列化此对象开始。一个人。

public class CTest
{
    public CTest Other { get; set; }
    public string Description { get; set; }
}

[Test]
public void Circulartest()
{
    CTest instance = new CTest();
    instance.Description = "Hello";
    instance.Other = instance;

    JsonConvert.SerializeObject(instance);
}

This would result in following JSON file

这将导致以下JSON文件

{
    "Description": "Hello"
    "Other":
    {
        "Description": "Hello"
        "Other":
        {
            "Description": "Hello"
            "Other":
            {
                "Description": "Hello"
                "Other":
                {
                    ....never ending story
                }
            }
        }
    }
}