简体   繁体   中英

Why does the behavior differ between VB.net and C#?

As for as I can tell the following two example are the same in terms of functionality.

C#

namespace ConsoleApplication4
{
 class Program
 {
  static void Main(string[] args)
  {
   var x = new Example(12);
   var y = new Example(34);
   var z = Example.Examples.One;
  }
 }
 class Example
 {
  public static class Examples
  {
   public static readonly Example Zero = new Example(0);
   public static readonly Example One = new Example(1);
  }
  public readonly Double Value;
  public Example(Double Value)
  {
   this.Value = Value;
  }
  public static Example Add(Example x, Example y)
  {
   return new Example(x.Value + y.Value);
  }
 }
}

VB.net

Option Strict On
Module Module1

    Sub Main()

    Dim x=New Example(12)
    Dim y = New Example(34)
    Dim z=  Example.Examples.One
    End Sub

End Module

Public Class Example

  Public  Class Examples
    Public Shared ReadOnly Zero As Example
    Public Shared ReadOnly One As Example
    Public Shared ReadOnly Two As Example
    Public Shared ReadOnly MinusOne As Example
    Shared Sub new()
      Zero=New Example(0)
      One= New Example(1)
      Two = New Example(2)
      MinusOne = New Example(-1)
    End Sub
  End Class
  Public ReadOnly Value As Double
  Public Sub New(Value As Double)
    Me.Value=Value
  End Sub
  Public Shared Function Add(x As Example,y As Example) As Example
    Return New Example(x.Value+y.Value)
  End Function
End Class

So why do I get only the instance methods in C# after the dot (see below)

z = Example.Examples.One.

and in VB.net

Dim z = Example.Examples.One.

I also get the Examples

What is going on? Why the difference?

For compatibility reasons, VB.Net alows you to access Shared ( static ) methods through an instance qualifier.
Don't do it; it's confusing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM