扩展方法不起作用?
我正在尝试使用
public static string TryGetRequestValue(this HttpRequest stringArg, int maxLengthArg)
{
return null;
}
As 扩展方法,但它不起作用,我收到错误消息“没有重载方法 TryGetRequestValue”等...
但是,当我取出 HttpRequest arg 并将其更改为字符串时,它可以工作。 ……这是为什么?
非常感谢任何帮助。
I'm trying to use
public static string TryGetRequestValue(this HttpRequest stringArg, 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅我在该问题下的评论,但基于此声明:
扩展方法中的第一个参数 - 以
this
为前缀的参数 - 确定要扩展的类型。因此,调用此方法的预期方式是:该方法返回一个
字符串
,并且仅采用一个参数:maxLengthArg
。如果您已经知道这么多,我深表歉意 - 发布引发异常的代码以及异常本身,将使这一点更清楚。
See my comment under the question, but based on this statement:
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: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.
由于 HttpRequest 对象的 Params 集合是 NameValueCollection 类型的集合,因此您无法直接检查某些键是否存在。但是此类具有 AllKeys 属性,该属性返回键数组,您可以使用 Linq 来检查键是否存在并通过 Get( ) 方法:
然后您可以按如下方式调用该方法:
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:
Then you can invoke the method as follows: