Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以在这里使用c#开关吗?_C#_Asp.net - Fatal编程技术网

我可以在这里使用c#开关吗?

我可以在这里使用c#开关吗?,c#,asp.net,C#,Asp.net,我想重构这段代码。如果可能的话,可以用开关吗?还是在性能方面是一样的 string rawUrl = context.Request.RawUrl ?? string.Empty; if (rawUrl.Contains("mypage.aspx")) { } if (rawUrl.Contains("mypage2.aspx")) { } etc.. 一点也不 尝试单独隔离页面名称,您可以做到这一点 switch(pageName) { case "mypage.aspx";

我想重构这段代码。如果可能的话,可以用开关吗?还是在性能方面是一样的

string rawUrl = context.Request.RawUrl ?? string.Empty;

if (rawUrl.Contains("mypage.aspx"))
{
}

if (rawUrl.Contains("mypage2.aspx"))
{
}

etc..
一点也不

尝试单独隔离页面名称,您可以做到这一点

switch(pageName)
{
    case "mypage.aspx";
        break;

    case "mypage2.aspx";
        break;
}

开关箱必须为常量值。您最好使用if/else这样的选项:

string rawUrl = context.Request.RawUrl ?? string.Empty;

if (rawUrl.Contains("mypage.aspx"))
{
    //code
}
else if (rawUrl.Contains("mypage2.aspx"))
{
    //more code
}
如果你关心性能(这很好!),那么其他的方法就是了。虽然不使用else将具有相同的功能,但通过添加else,您告诉代码不要处理任何其他if条件。所以10个if语句将得到10个if条件,不管处理什么,而10个if/else语句可能会得到10个if条件,或者可能只得到1个if条件

编辑:

仔细想想,我注意到你在使用上下文对象。如果确实需要switch语句,可以执行以下操作:

string page = context.Request.Url.Segments.Last();

switch(page)
{
    case "mypage.aspx":
        //code
        break;
    case "mypage2.aspx":
        //more code
        break;
}

不是直接的,因为您想要一个“包含”关系,而不是一个完全相等的关系

但是,如果您愿意,您可以通过尝试从我假定的URL解析页面名称,将其存储在单独的
字符串
变量中,然后打开该
字符串
来间接实现

例如:

// Get the URL from some external source (wherever you're already getting it from)
String rawUrl = "http://www.example.com/foo/bar.aspx";

// Means of parsing will be dependent on the format in which you expect the URL.
String page = rawUrl.Substring(rawUrl.LastIndexOf("/") + 1);

switch (page) {
    case "bar.aspx":
        // Do stuff
        break;
    case "foo.aspx":
        // Do stuff
        break;
}

当然,请对这种解析方法持保留态度;本例旨在向您展示这是可能的,但请注意,这种解析方法可能会在许多情况下引发异常,但为了简洁起见,我省略了这些检查。

我认为最好使用
字典

首先,从原始url提取文件名

然后,使用
词典

如果对页面的操作几乎相同,请将
TValue
设置为与页面关联的数据类型


如果操作非常不同,请将
TValue
设置为代理类型,例如
Action

nnnnop。。。。。。。我会使用elseif,可能更好。我不认为您可以在contains上执行切换,而是您必须解析页面名称的原始URL,或者如果可能的话,您必须将大小写设置为完整URL。是否可以使用
?这将有助于提高绩效