开发者

generic out value assignment inside try block

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 (Str开发者_C百科ing.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));
}


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 in ChangeType) without giving it a value.

In this case, maybe:

catch
{
    parsedValue = default(T);
    page.Response.RedirectPermanent(RedirectUrl);        
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜