代码之家  ›  专栏  ›  技术社区  ›  Tom Ritter

vb.net和c“作为新WebControl”的区别

  •  2
  • Tom Ritter  · 技术社区  · 17 年前

    我正在重构一些代码,其中的一部分包括将它从vb.net移动到c。

    旧代码声明了这样的成员:

    Protected viewMode As New WebControl
    

    新的代码,我终于开始工作了,像这样:

    protected WebControl _viewMode = new WebControl(HtmlTextWriterTag.Span);
    

    我可以假定 New 关键字的意思是:调用构造函数!但是,vb.net是如何调用一个在c中无法调用的构造函数(一个没有参数的构造函数)的呢?

    4 回复  |  直到 10 年前
        1
  •  9
  •   Scott Wisniewski    17 年前

    这在VB中工作而不是在C中工作的原因与程序集无关。

    WebControl的默认构造函数受到保护。

    vb和c对“受保护”的含义有不同的解释。

    在VB中,可以从从类派生的任何类型的任何方法访问类的受保护成员。

    也就是说,vb允许此代码编译:

    class Base
        protected m_x as integer
    end class
    
    class Derived1
        inherits Base
        public sub Foo(other as Base)
            other.m_x = 2
        end sub
    end class
    
    class Derived2
        inherits Base
    end class
    

    因为“derived1”是基,所以它可以访问“other”的受保护成员,后者也是基。

    C采取了不同的观点。它不允许“横向”访问,就像vb那样。 它表示,可以通过“this”或与包含该方法的类类型相同的任何对象来访问受保护的成员。

    因为这里的“foo”是在“derived1”中定义的,C只允许“foo”从“derived1”实例访问“base”成员。“其他”可能不是“派生的1”(例如,它可以是“派生的2”),因此它不允许访问“m_x”。

    在您的代码中,vb允许“侧向”访问“webcontrol”构造函数。

    但是,C没有。

        2
  •  2
  •   Rex M    17 年前

    WebControl(隐式在VB行中)的默认构造函数是使用范围。您可以在C和vb.net中调用该构造函数。

        3
  •  1
  •   Mikhail G    15 年前

    在任何上下文中从派生类访问继承的受保护构造函数都会引发数据封装问题。

    历史上,C因为第一个版本允许这样的访问。但它在2005年被修正了。派生类现在只能从自己的构造函数调用它们的受基保护的构造函数。

    class Base
    {
        protected Base()
        {
        }
    }
    
    class Derived : Base
    {
        public Derived() : base() // Still allowed in VS 2005
        {
        }
    
        public void Main()
        {
            Base b = new Base(); // Allowed in VS 2003, but error in VS 2005
        }
    }
    

    在vb.net中,可以通过两种方式初始化变量。首先是赋值运算符,然后是声明;其次是“as new”语句。

    对于受保护的构造函数,“as new”总是可以正常工作。对于通过赋值进行初始化,它将引发编译错误。但是,如果您在基类中有多个构造函数,那么分配初始化也将工作!

    Class Base
        Protected Sub New()
        End Sub
    End Class
    
    Class Derived
        Inherits Base
    
        Public Sub Main()
            Dim foo As New Base // Allowed
            Dim moo As Base = New Base() // Error if Base has only one constructor
        End Sub
    End Class
    

    可能是因为vb.net允许这种访问与遗留代码兼容。

    更多细节: http://blogs.msdn.com/b/peterhal/archive/2005/06/29/434070.aspx

        4
  •  0
  •   tsilb    17 年前

    网络控制WC= 标签 ;