How can I call MemberwiseClone()?

寵の児 提交于 2019-12-05 20:54:19

问题


I'm confused about how to use the MemberwiseClone() method. I looked the example in MSDN and they use it trough the this keyword.

Why I can not call it directly as other objects' methods like GetType() or ToString()? Another related method that does not appear is ShallowCopy().

If they are part of the Object class why can't I see them?


回答1:


The MemberwiseClone() function is protected, so you can only access it through a qualifier of your own type.




回答2:


Here is an example, this is what I did and no problems so far.

public class ModelBase
{
    public T ShallowCopy<T>() where T : ModelBase
    {
        return (T)(MemberwiseClone());
    }
}

And call it like:

var cloned = User.ShallowCopy<User>();


来源:https://stackoverflow.com/questions/6066029/how-can-i-call-memberwiseclone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!