Can I detect whether I've been given a new object as a parameter?

前端 未结 9 599
日久生厌
日久生厌 2021-01-18 01:31

Short Version

For those who don\'t have the time to read my reasoning for this question below:

Is there any way to enforce a policy of "new obje

9条回答
  •  无人及你
    2021-01-18 02:07

    I can think of a way to do this, but I would definitely not recommend this. Just for argument's sake.

    What does it mean for an object to be a "new" object? It means there is only one reference keeping it alive. An "existing" object would have more than one reference to it.

    With this in mind, look at the following code:

        class Program
        {
            static void Main(string[] args)
            {
                object o = new object();
    
                Console.WriteLine(IsExistingObject(o));
                Console.WriteLine(IsExistingObject(new object()));
    
                o.ToString();  // Just something to simulate further usage of o.  If we didn't do this, in a release build, o would be collected by the GC.Collect call in IsExistingObject. (not in a Debug build)
            }
    
            public static bool IsExistingObject(object o)
            {
                var oRef = new WeakReference(o);
    
    #if DEBUG 
                o = null; // In Debug, we need to set o to null.  This is not necessary in a release build.
    #endif
                GC.Collect();
                GC.WaitForPendingFinalizers();
    
                return oRef.IsAlive;
            }
        }
    

    This prints True on the first line, False on the second. But again, please do not use this in your code.

提交回复
热议问题