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

前端 未结 9 598
日久生厌
日久生厌 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:14

    As a possible partial solution if you only wanted one of an object to be consumed by a method maybe you could look at a Singleton. In this way the method in question could not create another instance if it existed already.

    0 讨论(0)
  • 2021-01-18 02:15

    No, basically.

    There's really no difference between:

    var x = new ...;
    Foo(x);
    

    and

    Foo(new ...);
    

    and indeed sometimes you might convert between the two for debugging purposes.

    Note that in the DataRow/DataTable example, there's an alternative approach though - that DataRow can know its parent as part of its state. That's not the same thing as being "new" or not - you could have a "detach" operation for example. Defining conditions in terms of the genuine hard-and-fast state of the object makes a lot more sense than woolly terms such as "new".

    0 讨论(0)
  • 2021-01-18 02:23

    No. And if there is some reason that you need to do this, your code has improper architecture.

    0 讨论(0)
提交回复
热议问题