C# 无法访问受保护的成员“object.MemberwiseClone()”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2023210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:46:58  来源:igfitidea点击:

Cannot access protected member 'object.MemberwiseClone()'

c#clone

提问by Xenoprimate

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

我试图在我.MemberwiseClone()的自定义类上使用,但它抛出了这个错误:

Cannot access protected member 'object.MemberwiseClone()' via a qualifier of type 'BLBGameBase_V2.Enemy'; the qualifier must be of type 'BLBGameBase_V2.GameBase' (or derived from it)

What does this mean? Or better yet, how can I clone an Enemyclass?

这是什么意思?或者更好的是,我如何克隆一个Enemy类?

采纳答案by SLaks

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)

在任何类中X,您只能MemberwiseClone在 的实例上调用(或任何其他受保护的方法)X。(或派生自 的类X

Since the Enemyclass that you're trying to clone doesn't inherit the GameBaseclass that you're trying to clone it in, you're getting this error.

由于Enemy您尝试克隆的GameBase类没有继承您尝试将其克隆到的类,因此您会收到此错误。

To fix this, add a public Clonemethod to Enemy, like this:

要解决此问题,请向 中添加一个公共Clone方法Enemy,如下所示:

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

回答by ModMa

  • you can′t use MemberwiseClone() directly, you must implement it via derived class (recomended)
  • but, via reflection, you can cheat it :)
  • you can use this litle extension for the classes that not implement ICloneable:

    /// <summary>
    /// Clones a object via shallow copy
    /// </summary>
    /// <typeparam name="T">Object Type to Clone</typeparam>
    /// <param name="obj">Object to Clone</param>
    /// <returns>New Object reference</returns>
    public static T CloneObject<T>(this T obj) where T : class
    {
        if (obj == null) return null;
        System.Reflection.MethodInfo inst = obj.GetType().GetMethod("MemberwiseClone",
            System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        if (inst != null)
            return (T)inst.Invoke(obj, null);
        else
            return null;
    }
    
  • 不能直接使用 MemberwiseClone(),必须通过派生类实现(推荐)
  • 但是,通过反射,你可以欺骗它:)
  • 您可以将这个小扩展用于未实现 ICloneable 的类:

    /// <summary>
    /// Clones a object via shallow copy
    /// </summary>
    /// <typeparam name="T">Object Type to Clone</typeparam>
    /// <param name="obj">Object to Clone</param>
    /// <returns>New Object reference</returns>
    public static T CloneObject<T>(this T obj) where T : class
    {
        if (obj == null) return null;
        System.Reflection.MethodInfo inst = obj.GetType().GetMethod("MemberwiseClone",
            System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        if (inst != null)
            return (T)inst.Invoke(obj, null);
        else
            return null;
    }
    

回答by Dinis Cruz

here is an extension method that allows the cloning of any object (use with the caveat that it not work in all cases)

这是一个允许克隆任何对象的扩展方法(使用时需要注意它不适用于所有情况)

public static class Extra_Objects_ExtensionMethods
{
    public static T clone<T>(this T objectToClone)
    {
        try
        {
            if (objectToClone.isNull())
                "[object<T>.clone] provided object was null (type = {0})".error(typeof(T));
            else
                return (T)objectToClone.invoke("MemberwiseClone");
        }
        catch(Exception ex)
        {
            "[object<T>.clone]Faild to clone object {0} of type {1}".error(objectToClone.str(), typeof(T));
        }
        return default(T);
    }   
}