String.MemberwiseClone() method called through reflection doesn't work, why?

最后都变了- 提交于 2019-12-07 15:18:45

问题


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);
}

And if I call it like this:

string str = ShallowClone("My string");

The resulting string (str) will be:

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

Thanks in advance!


回答1:


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.



来源:https://stackoverflow.com/questions/10644644/string-memberwiseclone-method-called-through-reflection-doesnt-work-why

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