通过反射调用的 String.MemberwiseClone() 方法不起作用,为什么? [英] String.MemberwiseClone() method called through reflection doesn't work, why?

查看:51
本文介绍了通过反射调用的 String.MemberwiseClone() 方法不起作用,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先让我说我知道它是一个受保护的方法,我不应该调用它,但它不应该工作,因为 MemberwiseClone 是在 Object<中定义的/strong> 类和 String 继承自它?

Let me start by saying that I know it is a protected method and I'm not supposed to call it, but shouldn't it work since MemberwiseClone is defined in the Object class and String inherits from it?

所以这是克隆方法(我删除了空引用处理以专注于重要的事情):

So this is the cloning method (I removed null reference handling to focus on what's important):

public static T ShallowClone<T>(T obj)
{
    MethodInfo memberwiseClone;
    memberwiseClone = obj.GetType().GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);
    return (T)memberwiseClone.Invoke(obj, null);
}

如果我这样称呼它:

string str = ShallowClone("My string");

结果字符串 (str) 将是:

The resulting string (str) will be:

"M\0\0\0\0\0\0\0\0"

提前致谢!

推荐答案

您正在调用它并且它正在工作.问题是 String.MemberwiseClone 没有做你期望它做的事情.它似乎创建了一个与原始字符串长度相同的字符串,但只复制了第一个字符.

You are calling it and it is working. The problem is that String.MemberwiseClone is not doing what you are expecting it to do. It appears to create a string with the same length as the original string, but only copies over the first character.

我认为这里要吸取的教训是:当你调用一个你不应该调用的方法时,要非常小心,了解它的作用,不要假设太多.

I think the lesson to be learned here is: When you call a method you're not supposed to call, be very careful, learn what it does, and don't assume too much.

这篇关于通过反射调用的 String.MemberwiseClone() 方法不起作用,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆