try 块内的通用输出值分配
我正在尝试编译以下代码:
public static void RequireOrPermanentRedirect<T>(this System.Web.UI.Page page, string QueryStringKey, string RedirectUrl, out T parsedValue)
{
string QueryStringValue = page.Request.QueryString[QueryStringKey];
if (String.IsNullOrEmpty(QueryStringValue))
{
page.Response.RedirectPermanent(page.ResolveUrl(RedirectUrl));
}
try
{
parsedValue = (T)Convert.ChangeType(QueryStringValue, typeof(T));
}
catch
{
page.Response.RedirectPermanent(RedirectUrl);
}
}
但我收到编译器错误:
Error 1 The out parameter 'parsedValue' must be assigned to before control leaves the current method
它是我已经使用了一段时间的扩展方法,但我想稍微扩展它,这样我就不必重新解析该值来使用它页面内。
当前用法:
Page.RequireOrPermanentRedirect<Int32>("TeamId", "Default.aspx");
int teamId = Int32.Parse(Request.QueryString["TeamId"]);
我想要做什么:
private Int32 teamId;
protected void Page_Load(object sender, EventArgs e)
{
Page.RequireOrPermanentRedirect<Int32>("TeamId", "Default.aspx", out teamId);
}
我刚刚创建并丢弃一个 T 值
的当前(工作)代码:
try
{
T value = (T)Convert.ChangeType(QueryStringValue, typeof(T));
}
I am trying to compile the following code:
public static void RequireOrPermanentRedirect<T>(this System.Web.UI.Page page, string QueryStringKey, string RedirectUrl, out T parsedValue)
{
string QueryStringValue = page.Request.QueryString[QueryStringKey];
if (String.IsNullOrEmpty(QueryStringValue))
{
page.Response.RedirectPermanent(page.ResolveUrl(RedirectUrl));
}
try
{
parsedValue = (T)Convert.ChangeType(QueryStringValue, typeof(T));
}
catch
{
page.Response.RedirectPermanent(RedirectUrl);
}
}
But I am getting a compiler error:
Error 1 The out parameter 'parsedValue' must be assigned to before control leaves the current method
Its an extension method which I have been using for a while but I wanted to extend it a little bit so that I didnt have to reparse the value to use it inside the page.
Current usage:
Page.RequireOrPermanentRedirect<Int32>("TeamId", "Default.aspx");
int teamId = Int32.Parse(Request.QueryString["TeamId"]);
What I wanted to be able to do:
private Int32 teamId;
protected void Page_Load(object sender, EventArgs e)
{
Page.RequireOrPermanentRedirect<Int32>("TeamId", "Default.aspx", out teamId);
}
The current (working) code I have just creates and throws away a T value
:
try
{
T value = (T)Convert.ChangeType(QueryStringValue, typeof(T));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该方法很好,但您需要在发生
Exception
的情况下执行某些操作,因为您不会重新抛出。这意味着您可以退出该方法(在ChangeType
中发生异常之后)而不为其赋值。在这种情况下,也许:
The method is fine, but you need to do something in the case that an
Exception
happens, since you don't re-throw. That means you could exit the method (after an exception inChangeType
) without giving it a value.In this case, maybe: