从Python到C#的异常处理让我烦恼的一件事是,在C#中似乎没有任何指定else子句的方法.例如,在Python中我可以写这样的东西(注意,这只是一个例子.我不是问什么是读取文件的最佳方法):
try
{
reader = new StreamReader(path);
}
catch (Exception)
{
// Uh oh something went wrong with opening the file for reading
}
else
{
string line = reader.ReadLine();
char character = line[30];
}
Run Code Online (Sandbox Code Playgroud)
从我在大多数C#代码中看到的,人们只会写下面的内容:
try
{
reader = new StreamReader(path);
string line = reader.ReadLine();
char character = line[30];
}
catch (Exception)
{
// Uh oh something went wrong, but where?
}
Run Code Online (Sandbox Code Playgroud)
这样做的问题在于我不希望因为文件中的第一行不能包含超过30个字符而超出范围异常.我只想捕获与读取文件流有关的异常.我可以在C#中使用任何类似的构造来实现相同的功能吗?
如果我在名为"AssemblyA"的程序集中有一个名为"MyClass"的类,并使用.NET的BinaryFormatter将其序列化为一个文件.然后将"MyClass"的代码移动到名为"AssemblyB"的程序集中,并尝试反序列化该文件,我得到以下"System.TypeLoadException"异常:
无法从程序集'AssemblyA,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'加载类型'AssemblyA.MyClass'.
有没有办法让我表明该课程已被移至AssemblyB?通过某种属性?或者是否可以将序列化文件修改为预处理步骤,以将AssemblyA.MyClass中的所有引用更改为AssemblyB.MyClass?最后,如果这些选项都不可能,是否可以绕过尝试反序列化该类并继续反序列化其余数据?