我刚开始使用Razor而不是WebForms-ViewEngine.现在在我的Razor-View中我有这样的事情:
@{
int i = 42;
string text;
if (i == 42)
{
text = "i is 42!";
}
else //i is not 42 //<- Error here
{
text = "i is something else";
}
}
Run Code Online (Sandbox Code Playgroud)
我得到一个警告,在运行时它在else行中得到一个异常:
期望"{"但找到"/".块语句必须用"{"和"}"括起来.您不能在CSHTML页面中使用单语句控制流语句.
显然,编译器不喜欢else和{之间的注释.我也尝试用@*和/*进行评论,它给出了类似的错误消息.
反正有没有像我想要的那样在剃刀上发表评论?
是的我知道我可以像这样解决它:
@{
int i = 42;
string text;
if (i == 42)
{
text = "i is 42!";
}
else
{ //i is not 42
text = "i is something else";
}
}
Run Code Online (Sandbox Code Playgroud)
但是它不符合我们的编码指南,并且对同一行的评论使我的意图更加明确.
我有一个对象.通常它是long或者string,所以为了简化代码,让我们假设它.
我必须创建一个方法,尝试将此对象转换为提供的枚举.所以:
public object ToEnum(Type enumType, object value)
{
if(enumType.IsEnum)
{
if(Enum.IsDefined(enumType, value))
{
var val = Enum.Parse(enumType, (string)value);
return val;
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
使用字符串它很好.随着数字它会导致问题,因为一个默认基础类型是枚举int,而不是long和IsDefined抛出ArgumentException.
当然,我可以做很多检查,转换或尝试捕获.
我想要的是拥有一个干净而小巧的代码.任何想法如何使其可读和简单?
我有几个C#方法,我想包装在try-catch块中.每个函数对catch都有相同的逻辑.有没有一种优雅的方法来为这些函数添加一个装饰器,所以它们都用相同的try/catch块包装?我不想将try/catch块添加到所有这些函数中.
例:
public void Function1(){
try {
do something
}catch(Exception e) {
//a BUNCH of logic that is the same for all functions
}
}
public void Function2() {
try {
do something different
}catch(Exception e) {
//a BUNCH of logic that is the same for all functions
}
}
Run Code Online (Sandbox Code Playgroud) 我需要在我的应用程序中使用信号量,其中包括多个线程.我的用法可能是常见的情况,但我坚持使用API.
在我的使用中,信号量可以从多个位置发布,而只有一个线程在信号量上等待.
现在,我要求信号量是二进制信号,即,我需要确保在多个线程同时发布到信号量的情况下,信号量计数保持为1,并且不会抛出任何错误.我怎样才能做到这一点.
简而言之,我需要以下代码才能工作.
private static Semaphore semaphoreResetMapView = new Semaphore(0, 1); // Limiting the max value of semaphore to 1.
void threadWait(){
while (true){
semaphoreResetMapView.WaitOne();
<code>
}
}
void Main(){
tThread = new Thread(threadWait);
tThread.Start();
semaphoreResetMapView.Release(1);
semaphoreResetMapView.Release(1);
semaphoreResetMapView.Release(1); // Multiple Releases should not throw an error. Rather saturate the value of semaphore to 1.
}
Run Code Online (Sandbox Code Playgroud)
我将不胜感激任何帮助.
我有以下代码:
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
strCsv.Append( XC.CleanForCsv(ds.Tables[0].Rows[i][j].ToString()) + ",");
}
strCsv.Append( "\r\n" + strCsv)
}
Run Code Online (Sandbox Code Playgroud)
Dataset包含8000条记录.for仅在15条记录strCsv.Append( "\r\n" + strCsv)语句之后使用循环循环记录抛出异常说明System.OutOfMemoryException.这个例外背后的原因是什么?