我想不出一个好的头衔,但我的问题并不像它看起来那么幼稚.
考虑一下:
public static void ExitApp(string message)
{
// Do stuff
throw new Exception(...);
}
Run Code Online (Sandbox Code Playgroud)
要么
public static void ExitApp(string message)
{
// Do stuff
System.Environment.Exit(-1);
}
Run Code Online (Sandbox Code Playgroud)
这些方法都不会回归.但是当你在别处调用这些方法时:
public int DoStuff()
{
// Do stuff
if (foo == 0)
{
throw new Exception(...);
}
else if (foo == 1)
{
// Do other stuff
return ...;
}
else
{
ExitApp("Something borked");
}
}
Run Code Online (Sandbox Code Playgroud)
尝试编译它,你会在DoStuff中得到一个"并非所有代码路径都返回一个值".使用Exception来跟踪对ExitApp的调用似乎很愚蠢,只是为了满足编译器,即使我知道它很好.在ExitApp()中似乎没有任何东西可以表明它永远不会返回.
如何向编译器指示ExitApp永远不会返回,因此,DoStuff的else块也永远不会返回? 这似乎是一个相当简单的错误,它的路径检查无法解释.
即使我只使用第一个ExitApp(抛出异常)并且该方法返回一个int,路径检查器足够聪明,意识到它永远不会返回,所以它不会抱怨int类型.这个编译文件:
public static int ExitApp(string message)
{
// Do stuff
throw new …Run Code Online (Sandbox Code Playgroud) 可能重复:
我可以"乘"一个字符串(在C#中)吗?
在Python中我可以这样做:
>>> i = 3
>>> 'hello' * i
'hellohellohello'
Run Code Online (Sandbox Code Playgroud)
我怎样才能在C#中使用Python中的字符串? 我可以轻松地在for循环中执行它,但这会变得乏味且无表情.
最终我正在递归地写出控制台,每次调用都会递增缩进级别.
parent
child
child
child
grandchild
Run Code Online (Sandbox Code Playgroud)
这是最简单的事情"\t" * indent.
如果我有这两个类:
class A {}
class B : A {}
Run Code Online (Sandbox Code Playgroud)
我创建一个List <A>但是我想通过调用List <A> .AddRange(List <B>)向它添加List <B>,但编译器拒绝:
Argument '1': cannot convert from 'System.Collections.Generic.List<A>'
to 'System.Collections.Generic.IEnumerable<B>
Run Code Online (Sandbox Code Playgroud)
我完全理解,因为IEnumerable <B>不从IEnumerable <A>继承,其泛型类型具有继承性.
我的解决方案是枚举List <B>并单独添加项目,因为List <A> .Add(A item)将与B项一起使用:
foreach(B item in listOfBItems)
{
listOfAItems.Add(item);
}
Run Code Online (Sandbox Code Playgroud)
然而,那是相当不具有表现力的,因为我想要的只是AddRange.
我可以用
List<B>.ConvertAll<A>(delegate(B item) {return (A)item;});
Run Code Online (Sandbox Code Playgroud)
但这是不必要的错综复杂和用词不当,因为我没有转换,我正在施展.
问题:如果我要编写自己的类似List的集合,我将添加哪种方法,这将允许我将B的集合复制到A的集合中,作为类似于List <A> .AddRange(List <B>)并保持最大的类型安全性.(并且最大化我的意思是该参数既是集合又是类型的inhertance检查.)
对于我正在进行的项目,我试图传递一组对象,它们都以某种方式链接到一个对象.
我目前已经昏迷,似乎无法找到合适的解决方案.
情况就是这样.我有一个产品对象,适用一些保险套餐.我需要将此信息传递给视图,但我必须能够为正确的产品检索正确的包.所以它看起来像......
产品1具有包装1,2,3产品2具有包装2,3,5,6产品3具有包装2,4,6,7
问题是可能存在不同数量的产品和不同数量的包
有任何想法吗?答案可能很简单,但我有点太累了,无法找到它......