C# vb中Err的c等价

C# vb中Err的c等价,c#,vb.net,vb.net-to-c#,C#,Vb.net,Vb.net To C#,让我知道:如何访问C中的Err?这是要转换的示例VB代码: If Len(sPart1) <> PART1_LENGTH Then Err.Raise(vbObjectError, , "Part 1 must be " & PART1_LENGTH) ElseIf Not IsNumeric(sPart1) Then Err.Raise(vbObjectError, , "Part 1 must be numeric") 将Err.Raise替换为

让我知道:如何访问C中的Err?这是要转换的示例VB代码:

If Len(sPart1) <> PART1_LENGTH Then
    Err.Raise(vbObjectError,  , "Part 1 must be " & PART1_LENGTH)

ElseIf Not IsNumeric(sPart1) Then 
    Err.Raise(vbObjectError,  , "Part 1 must be numeric")
将Err.Raise替换为


假设您询问的是语法,而不是特定的类:

throw new SomeException("text");
你可以利用

  throw new Exception();

首先,让我们将其转换为现代VB代码:

If sPart1.Length <> PART1_LENGTH Then
  Throw New ApplicationException("Part 1 must be " & PART1_LENGTH)
ElseIf Not IsNumeric(sPart1) Then
  Throw New ApplicationException("Part 1 must be numeric")
End If

我知道在C和VB.NET中都应该使用异常,但对于后代来说,在C中使用ErrObject是可能的

OP程序转换为C的完整示例程序:

using Microsoft.VisualBasic;

namespace ErrSample
{
    class Program
    {
        static void Main(string[] args)
        {
            ErrObject err = Information.Err();

            // Definitions
            const int PART1_LENGTH = 5;
            string sPart1 = "Some value";
            int vbObjectError = 123;
            double d;

            if (sPart1.Length != PART1_LENGTH)
                err.Raise(vbObjectError, null, "Part 1 must be " + PART1_LENGTH);
            else if (!double.TryParse(sPart1, out d))
                err.Raise(vbObjectError, null, "Part 1 must be numeric");
        }
    }
}

这不仅仅是“使用异常”。在.NET中不应依赖于最初处理vb6垃圾的错误。了解异常,了解堆栈跟踪。若你们得到了你们想要的d信息,别忘了将答案标记为已接受。。。
int part;
if (sPart1.Length != PART1_LENGTH) {
  throw new ApplicationException("Part 1 must be " + PART1_LENGTH.ToString());
} else if (!Int32.TryParse(sPart1, out part)) {
  throw new ApplicationException("Part 1 must be numeric")
}
using Microsoft.VisualBasic;

namespace ErrSample
{
    class Program
    {
        static void Main(string[] args)
        {
            ErrObject err = Information.Err();

            // Definitions
            const int PART1_LENGTH = 5;
            string sPart1 = "Some value";
            int vbObjectError = 123;
            double d;

            if (sPart1.Length != PART1_LENGTH)
                err.Raise(vbObjectError, null, "Part 1 must be " + PART1_LENGTH);
            else if (!double.TryParse(sPart1, out d))
                err.Raise(vbObjectError, null, "Part 1 must be numeric");
        }
    }
}