关于C#:如何轻松编写克隆方法?


How to write a clone method easily?

我有一个带有虚拟克隆新方法的基类

1
2
3
4
class A
{
    virtual A* cloneNew() const { return new A; }
};

及其衍生物

1
2
3
4
5
6
7
8
9
class A1 : public A
{
    virtual A1* cloneNew() const { return new A1; }
};

class A2 : public A
{
    virtual A2* cloneNew() const { return new A2; }
};

现在我想使用宏或其他方式使它更容易重新实现,例如

1
2
3
4
class A1: public A
{
    CLONE_NEW; // no type A1 here
};

有可能做到吗? decltype(this)有帮助吗?


以下内容对我来说很好,并且可以轻松地转换为宏:

1
2
3
4
5
6
7
struct Foo
{
    virtual auto clone() -> decltype(this)
    {
        return new auto(*this);
    }
};

如果希望clone()函数为const,则不能使用new auto,并且必须更加努力地使用返回类型:

1
2
3
4
5
6
#include <type_traits>

virtual auto clone() const -> std::decay<decltype(*this)>::type *
{
    return new std::decay<decltype(*this)>::type(*this);
}