ASP.NET (VB) 扩展方法未按预期工作
我有以下扩展方法
Imports System.Runtime.CompilerServices
Namespace Extensions
Public Module IntegerExtensions
<Extension()>
Public Function ToCommaDeliminatedNumber(ByVal int As Integer) As String
Dim _input As String = int.ToString
Select Case int
Case Is > 99999 : Return _input.Remove(_input.Length - 3) & "k"
Case Is > 9999 : Return Math.Round(Double.Parse(int / 1000), 1).ToString & "k"
Case Is > 999 : Return String.Format("{0:N0}", int)
Case Else : Return _input
End Select
End Function
End Module
End Namespace
,在我正在使用的一个类中,
user.Reputation.ToCommaDeliminatedNumber
我将扩展命名空间导入到类中,但我得到的错误是......
“ToCommaDelimatedNumber”不是“Integer?”的成员。
有人能告诉我这里可能缺少什么吗?我确实有其他用于字符串和日期的扩展方法,它们完全按照预期工作......我只是对这个感到不知所措。
I have the following Extension Method
Imports System.Runtime.CompilerServices
Namespace Extensions
Public Module IntegerExtensions
<Extension()>
Public Function ToCommaDeliminatedNumber(ByVal int As Integer) As String
Dim _input As String = int.ToString
Select Case int
Case Is > 99999 : Return _input.Remove(_input.Length - 3) & "k"
Case Is > 9999 : Return Math.Round(Double.Parse(int / 1000), 1).ToString & "k"
Case Is > 999 : Return String.Format("{0:N0}", int)
Case Else : Return _input
End Select
End Function
End Module
End Namespace
And in one of my classes I'm using
user.Reputation.ToCommaDeliminatedNumber
I am importing the Extensions Namespace into the Class, but the error I'm getting is...
'ToCommaDeliminatedNumber' is not a member of 'Integer?'.
Can anybody tell me what I might be missing here? I do have other Extension Methods for Strings and Dates that work exactly as expected... I'm just at a loss on this one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从您的错误消息来看,基于尾随问号(“整数?”),
user.Reputation
实际上是一个Nullable(Of Integer)
。这是正确的吗?您的扩展方法正在扩展
Integer
,而不是Integer?
(即Nullable(Of Integer)
),因此出现错误。因此,要么提供一个处理Integer?
的重载,要么在可为 null 的类型上调用Value
:您需要检查它是否不为 null (
Nothing
) 否则会抛出异常。重载方法可能如下所示:如果它为 null,则将显示默认值 0。
Judging from your error message it looks like
user.Reputation
is actually aNullable(Of Integer)
, based on the trailing question mark ('Integer?'). Is that correct?Your extension method is extending
Integer
, notInteger?
(i.e.,Nullable(Of Integer)
), hence the error. So either provide an overload that handlesInteger?
or callValue
on the nullable type:You will need to check that it is not null (
Nothing
) otherwise an exception will be thrown. An overloaded method might look like this:In the case that it's null the default value of 0 would be displayed.