开发者

Extension method doesnt work?

I'm trying to use

public static string TryGetRequestValue(this HttpRequest str开发者_StackOverflowingArg, int maxLengthArg)
{
    return null;
}

As an extension method and it isn't working I get the error message 'No overload for method TryGetRequestValue' etc etc...

However when I take out the HttpRequest arg and change it to a string it works....Why is this?

Any help much appreciated.


See my comment under the question, but based on this statement:

However when I take out the HttpRequest arg and change it to a string it works....Why is this?

The first parameter in an extension method - the one prefixed with this - determines the type being extended. So the expected way to call this method would be:

HttpRequest instanceOfClassBeingExtended = new HttpRequest();
string returnValue = instanceOfClassBeingExtended.TryGetRequestValue(10000);

The method returns a string, and only takes one parameter: maxLengthArg.

Apologies if you already know this much - posting the code that's throwing the exception, as well as the exception itself, will make that clearer.


Because the Params collection of the HttpRequest object is a collection of the type NameValueCollection you can not directly check for the existence of some key. But this class has the AllKeys property that return an array of keys the you can use Linq to check the key existence and get the value by means of the Get() Method:

public static string TryGetRequestValue(this HttpRequest request, string stringArg)
{
    string result = null;
    string[] keys = request.Params.AllKeys;
    if( keys.Contains<string>(stringArg) )
    {
        result = request.Params.Get(stringArg);
    }   
    return result;
}

Then you can invoke the method as follows:

Request.TryGetRequestValue("someGetParam");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜