简体   繁体   中英

How to use VB.net Class in C# project?

I would like to use the below VB.Net class in my C# Project. Is there any way to do it?. Thanks in advance.

 Public Class XMLItemList
        Private sb As System.Text.StringBuilder

        Public Sub New()
            sb = New System.Text.StringBuilder
            sb.Append("<items>" & vbCrLf)
        End Sub

        Public Sub AddItem(ByVal Item As String)
            sb.AppendFormat("<item id={0}{1}{2}></item>{3}", Chr(34), Item, Chr(34), vbCrLf)
        End Sub

        Public Overrides Function ToString() As String
            sb.Append("</items>" & vbCrLf)
            Return sb.ToString
        End Function     
    End Class

You need to create VB.NET DLL assembly (using Library project template from Visual Studio) and then you can add the reference of DLL assembly to your C# project. Be sure that the only public types (classes) are visible outside the assembly.

Yes. Because both VB.NET and C# compile into IL (intermediate language), you can simply create a library (a DLL file) in VB.NET, and then use that library in C#.

It's better to translate it into C#, and to fix the broken ToString() implementation:

  using System.Xml;

  public class XMLItemList
  {
    XmlElement el;
    XmlDocument doc;

    public XMLItemList()
    {
      doc = new XmlDocument();
      el = doc.CreateElement("items");
    }

    public void AddItem(string item)
    {
      var itemXml = doc.CreateElement("item");
      var attr = doc.CreateAttribute("id");
      attr.Value = item;
      itemXml.Attributes.Append(attr);

      el.AppendChild(itemXml);

    }

    public override string ToString()
    {
      return el.OuterXml;
    }
  }

将类转换为C#或将类保存在类库中,并在C#项目中引用它。

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