开发者

Why doesn't C# support the concept of Copy Constructor?

I was as开发者_开发百科ked this question in one of my interviews, but I wasn't able to find out exactly why this concept is not there.

Please let me know.


It's not built into the language because there is not a reasonable default implementation.

Copy constructors suffer from many of the same ambiguities as cloning. For example, whether you want to make a shallow copy or a deep copy depends on your particular circumstances.

Say you have an Order class with a Customer property. Should its copy constructor create a new customer or point to the original instance? Probably the original instance - but what about Order.Payment?

Worse, even when you do want to perform a deep copy, you may even not be able to create all of your subordinate objects, because their constructors (or comparable factory methods) may not be accessible.

In case that's not enough, this article on Java Design Issues highlights some other problems (like type truncation).


In what way does C# not support the idea of a copy constructor? You're more than free to create one that copies as deep as you like.


Doesn't it?

class Foo
{
   public Foo (Foo other)   // copy ctor
   { ... }
}

But maybe I'm a bit rusty about what other rules apply in C++ (where the term copy constructor was coined).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜