加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

为什么我不能从vb.net中的公共共享方法调用私有共享方法?

发布时间:2020-12-17 00:07:24 所属栏目:大数据 来源:网络整理
导读:我有一个这样的课: class Foo private shared default_ = "DEFAULT" public shared function bar(val as object) as string if val is Nothing then return _default return getBar(val) end function private shared function getBar(val as string) as st
我有一个这样的课:
class Foo
    private shared default_ = "DEFAULT"

    public shared function bar(val as object) as string
        if val is Nothing then return _default

        return getBar(val)
    end function

    private shared function getBar(val as string) as string
        return formatString(val)
    end function

    private shared function getBar(val as System.Int32) as string
        return formatInt(val)
    end function
end class

formatString和FormatInt是公共共享方法.
当我调用Foo.bar时,我得到一个MissingMemberException:

System.MissingMemberException: Public member 'getBar' on type 'Foo' not found.

当我将getBar方法公开时,它可以工作,但我不想不必要地公开它们.为什么我不能从同一个类中的公共方法调用私有共享方法.

我在Web应用程序中使用.net framework 4.0.

您的公共方法将对象作为参数,您的私有方法采用字符串/整数.所以运行时不知道它应该使用哪个重载方法.

如果将所有重载方法设为公共,则只有在Option Strict关闭时才会编译代码.然后在运行时,不会抛出异常migth,因为对象的实际类型将通过后期绑定(或者甚至是静默地转换为匹配类型,从日期到字符串)来检测.但是,尽管如此,请使用Option Strict On避免使用late binding并使用VB.NET作为它应该是的类型:强类型语言.

主要原因 – 您的代码抛出具有Option Strict Off和私有方法的MissingMemberException的原因是:

>如果您尝试访问后期绑定对象变量的成员,请确保将其声明为Public(受保护,朋友和私有变量cannot be late-bound in Visual Basic)

您可以检查val的类型,将对象强制转换为此类型,然后将该参数传递给正确的方法.例如:

Public Overloads Shared Function bar(ByVal val As Object) As String
      If val Is Nothing Then Return default_

      If TypeOf val Is String Then
          Return getBar(CStr(val))
      ElseIf TypeOf val Is Int32 Then
          Return getBar(CInt(val))
      Else
          Return default_
      End If
End Function

另一点:如果您计划创建一个采用对象的扩展方法,forget it:

Mainly,we do not allow extension methods to be called off of any
expression that is statically typed as “Object”. This was necessary to prevent any > existing late bound code you may have written from being broken by extension methods

> http://msdn.microsoft.com/en-us/library/bb384936.aspx(寻找MissingMemberException)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读