目前我正在与那个"神奇的弦乐"问题作斗争:
public class MyDataField
{
// class definition
}
// exuecuted method
public void SwitchMultipleDataFields()
{
var myField = new MyDataField();
switch(myField.GetType().ToString())
{
// only case, which works
case "MyDataField":
// case operations
break;
// other option:
case typeof(MyDataField).ToString():
// case operations
break;
// other cases of other FieldTypes
}
}
Run Code Online (Sandbox Code Playgroud)
现在我收到错误消息我写在我的线程标题中.我认为问题是这个字符串不是"非编译时"的常量.因此,要求切换的唯一可能方法是通过明确确定该案例字符串的值.我的问题只是我没有得到编译错误,以防我重命名MyDataField该类.因此,无论如何,这些类中有90%是通用的.这些是在defaultswitch语句中处理的.除了明确确定案例值的价值之外,还有其他方法吗?
请不要争论这种方法的意义.我刚刚写了这篇文章以便更简单地说明我的问题
给出以下类:
public interface ISession {}
public class Session : ISession
{
internal Uri ServerUri { get; private set; } // not in interface obviously
}
Run Code Online (Sandbox Code Playgroud)
现在我在同一个项目中有另一个类依赖于Session:
public interface IDataClass {}
internal DataClass : IDataClass
{
private readonly Session _session;
public DataClass(ISession session)
{
_session = (Session) session;
}
// some more methods that access the internal property _session.ServerUri
// and call methods on the session object
// ...
}
Run Code Online (Sandbox Code Playgroud)
实际上,Session类非常复杂.对于单元测试,DataClass我创建了构造函数参数ISession,因此我能够模拟依赖项并验证ISession模拟上的某些方法调用.
但是,有些方法DataClass …
在.NET中是否有一个方法,它会在一个字符串的路径末尾自动附加一个反斜杠?
就像是:
var path = @"C:\Windows";
path = Path.GetPathWithSeperatorAtTheEnd(path);
Console.WriteLine(path);
// outputs C:\Windows\
Run Code Online (Sandbox Code Playgroud)
我现在做的是:
if (!path.EndsWith(@"\")) path += @"\";
Run Code Online (Sandbox Code Playgroud)
编辑:我想要实现的是,如果我将文件名附加到一个我不需要担心的路径,那就会发生这样的事情.或者是否有另一种方法而不是追加路径和文件名?
var fullFilename = path + filename;
// path : C:\Windows
// filename: MyFile.txt
// result : C:\WindowsMyFile.txt
Run Code Online (Sandbox Code Playgroud) 我找不到有关打字稿中的抛出语法的任何信息,所以我只是想知道这两个语义是否在语义上相同?从我测试的两种方法保持callstack.
try {
throw new Error("You can't recover from this.");
} catch (e) {
console.error(e);
throw e;
}
try {
throw new Error("You can't recover from this.");
} catch (e) {
console.error(e);
throw(e);
}
Run Code Online (Sandbox Code Playgroud)
在C#中这样做会踩到callstack,所以我只想绝对肯定.正确的C#方式是这样的:
try {
throw new Exception("You can't recover from this.");
catch (Exception e)
_logger.LogError(e);
throw;
}
Run Code Online (Sandbox Code Playgroud)