当方法采用对象 C# 时,字符串作为引用参数出现问题
可能的重复:
C#:为什么“ref”和“out”不支持多态性?
我似乎无法理解为什么以下内容在 C# 中不起作用:
public static void Swap(ref Object a, ref Object b) {
Object t = b;
b = a;
a = t;
}
//Calls
String fname = "Ford";
Strinf lname = "James";
Swap(ref lname, ref fname);
这是因为 String 已经引用了 char 数组,它是不可变的吗?
Possible Duplicate:
C# : Why doesn't 'ref' and 'out' support polymorphism?
I can't seem to understand why the following does not work in C#:
public static void Swap(ref Object a, ref Object b) {
Object t = b;
b = a;
a = t;
}
//Calls
String fname = "Ford";
Strinf lname = "James";
Swap(ref lname, ref fname);
Is this because String already references to a char array, its immutable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
的重复
这是为什么不'ref' 和“out”支持多态性?
请参阅该答案以了解为什么它不起作用。
为了使其工作,您可以创建一个通用方法:
现在所有类型都将被检查。
This is a duplicate of
Why doesn't 'ref' and 'out' support polymorphism?
See that answer for why it doesn't work.
To make it work, you could make a generic method:
And now all the types check out.
我再次必须链接到 Eric Lippert 的博客文章(今天第二次!)关于这个主题:
为什么 ref 和 out 参数不允许类型变化?
基本上允许这种转换会破坏类型安全,因为您可以更改对象引用来保存与调用者传入的任何类型都不匹配的另一种类型。
I once again have to link to a blog post by Eric Lippert (second time today!) on this very topic:
Why do ref and out parameters not allow type variation?
Basically allowing this conversion would break type safety since you could change the object reference to hold another type that doesn't match whatever type the caller passed in.
这应该无法编译,谢天谢地是这样。想象一下,您在 swap 方法中将一个整数放入对象 a 或 b 中。这根本不可能,因为实际引用是字符串类型的对象。
您可能会在 JavaScript 或 PHP 等动态类型脚本语言中实现这种行为,因为无论如何,一切都只是一个“var”。但在 C# 这样的静态类型语言中,这是不可能的。
This should not be able to compile, and thankfully so. Imagine you put an integer into object a or b, in the swap method. That wouldn't be possible at all, because the actual reference is to an object of type string.
You might pull this kind of behavior off in a dynamically typed scripting language like JavaScript or PHP, because everything is just a 'var' anyway. But in a statically typed language like C#, this is impossible.