Cannot access protected member 'object.MemberwiseClone()'

后端 未结 3 1484
太阳男子
太阳男子 2020-12-15 16:52

I\'m trying to use .MemberwiseClone() on a custom class of mine, but it throws up this error:

Cannot access protected member \'object.Memberwise         


        
3条回答
  •  囚心锁ツ
    2020-12-15 17:49

    Within any class X, you can only call MemberwiseClone (or any other protected method) on an instance of X. (Or a class derived from X)

    Since the Enemy class that you're trying to clone doesn't inherit the GameBase class that you're trying to clone it in, you're getting this error.

    To fix this, add a public Clone method to Enemy, like this:

    class Enemy : ICloneable {
        //...
        public Enemy Clone() { return (Enemy)this.MemberwiseClone(); }
        object ICloneable.Clone() { return Clone(); }
    }
    

提交回复
热议问题