【发布时间】:2019-10-08 16:44:35
【问题描述】:
我目前正在学习 c# 中 try、switch、异常的正确用法,我问自己是否可以在 = 运算符处引发异常。
我搜索了一些并找到了https://referencesource.microsoft.com/#mscorlib/system/string.cs 这应该是字符串类的实现,但我在此代码中找不到 =operator 定义。我在哪里可以在我自己的系统上找到我自己的 string.cs 类实现?我只找到了这个在线版本。
string line = Console.ReadLine();
//Console.ReadLine() can throw ArgumentOutOfRangeException,
//OutOfMemoryException or IOException.
//but what can the = operator throw?
//what will happen in the following code?
string l = "Very Very extreme long long text";
如何处理 100% 正确?
【问题讨论】:
-
=不是可重载的运算符。=运算符可以导致发生隐式用户定义的转换,这可能会引发异常,但这并不完全相同。 -
内部如何定义=操作符?系统知道什么字符串 s = "str";意思是
-
=运算符总是要么只是将一个值复制到一个变量,要么调用一个属性设置器或一个索引器。它不是基于每种类型定义的。 -
好的。我找到了stackoverflow.com/questions/3436101/create-custom-string-class。您可以使用隐式对话来做到这一点,但在许多情况下这不是一个好主意。
标签: c# string exception crash operator-keyword