且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

可C#编译器编译一个VB.Net code?

更新时间:2023-11-10 20:40:28

他们有独立的编译器(csc.exe的C#和VBC.EXE为VB.Net),但它们都被编译成IL,然后在运行时JIT它编译成机器code。

They have separate compilers (csc.exe for C# and vbc.exe for VB.Net) but they both get compiled into IL and then at run-time JIT compiles it into machine code.

问题1:可以C#编译器编译VB.net code?

Question 1 : can C# compiler compile VB.net code?

答1:不,不可能,你会看到,在下面的例子。如果你尝试这样做,因为它看起来对C#语法它给出了一个错误。

Answer 1: No it can't and you will see that in the below example. It gives an error if you try to do that as it looks for C# syntax.

问题2:我想这就是他们在书中说。既然是两个编译器,我觉得它是不兼容的。

Question 2: I think that's what they say in the book. Since it is two compilers, I feel it is not compatible

答2:这并不是说,你可以使用C#编写VB code,但它说,你可以像我一样,在下面的例子中,仍然能够编译C#和VB混合语言在一个单一的应用程序(用他们的编译器)。

Answer 2: It doesn't say that you can compile VB code using C# but it says that you can mix languages in a single application like I did in the example below and still able to compile C# and VB (using their compilers).

请参阅下面的例子来理解它是如何工作的。我创建了一个C#项目与C#类和VB项目与VB类的解决方案。你不应该将C#和VB类相同的项目,因为它会忽略构建过程中的VB文件,如果它是一个C#项目。

See below example to understand how it works. I created a solution with a C# project with a C# class and a VB project with a VB class. You should not mix C# and VB classes in same project as it will ignore the vb file if its a C# project during build.

可C#编译器编译一个VB.Net code?

ClassCSharp.cs的内容:

Content of ClassCSharp.cs:

namespace ClassLibraryCSharp
{
    public abstract class ClassCSharp
    {
        public int MyProperty { get; set; }

        protected abstract void Test();
    }
}

ClassVBInCSharp.vb在C#ClassLibrary

内容。看我怎么可以从C#类继承,并访问其属性和覆盖的方法。

Content of ClassVBInCSharp.vb in C# ClassLibrary. See how I can inherit from a C# class and also access its properties and override the method.

Namespace ClassLibraryVB
    Public Class ClassVBInCSharp
        Inherits ClassCSharp
        Property Test2 As Integer

        Protected Overrides Sub Test()
            Test2 = MyBase.MyProperty
        End Sub
    End Class
End Namespace

请参阅下面的命令,我跑:

See below commands I ran:

vbc.exe /reference:"ClassLibraryCSharp.dll" /target:library /out:"ClassLibraryCSharpVbVersion.dll" "ClassVBInCSharp.vb"
Microsoft (R) Visual Basic Compiler version 12.0.20806.33440
Copyright (c) Microsoft Corporation.  All rights reserved.

请参阅上面的VB编译器来编译VB类。

See above VB Compiler is used to compile vb class.

csc.exe /reference:"ClassLibraryCSharp.dll" /target:library /out:"ClassLibraryCSharpVersion.dll" "ClassVBInCSharp.vb"
Microsoft (R) Visual C# Compiler version 4.0.30319.33440 for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.

ClassLibrary1\ClassVBInCSharp.vb(1,1): error CS
0116: A namespace cannot directly contain members such as fields or methods

见上面,如果我尝试使用C#编译器,它抛出一个错误,因为它寻找C#语法编写VB类。

See above if I try to use C# Compiler to compile vb class it throws an error as its looking for C# syntax.