What is the .NET object life cycle?

前端 未结 9 2126
一个人的身影
一个人的身影 2020-12-29 09:05

What is the object life cycle for an object in .NET?

From what I understand it is:

  1. Object created - constructor called (if one exists)
  2. Methods
9条回答
  •  灰色年华
    2020-12-29 09:11

    Just as an edge case... you can create objects without using the ctor at all:

    class Foo {  
        public Foo() {
            message += "; ctor";
        }
        string message = "init";
        public string Message { get { return message; } }
    }
    static class Program {
        static void Main() {
            Foo foo = new Foo();
            Console.WriteLine(foo.Message); // "init; ctor"
            Foo bar = (Foo)System.Runtime.Serialization.FormatterServices
                .GetSafeUninitializedObject(typeof(Foo));
            Console.WriteLine(bar.Message); // null
        }
    }
    

提交回复
热议问题