如何在c#中定义类型变体?

时间:2015-04-21 08:16:58

标签: c# asp.net-mvc vb.net

我在我的MVC项目业务对象类中使用了一个VB函数。

VB中的示例代码:

Dim vntPF As Variant
Const INT_PF_USER = 0
Const INT_PF_VENDOR = 1
  strPFUser = ""
  strPFVendor = ""
If (InStr(1, strMerchId, "~") > 0) Then
  vntPF = Split(strMerchId, "~") 
  strPFUser = vntPF(INT_PF_USER)
  strPFVendor = vntPF(INT_PF_VENDOR)
Else
  strPFUser = strMerchId
  strPFVendor = strMerchId
End If

我想在C#类中使用相同的代码。

**Dim vntPayFlow As Variant**

  string strPFUser = string.Empty;
  string strPFVendor = string.Empty;
const int INT_PF_USER = 0;
const int INT_PF_VENDOR = 1;
if (Strings.InStr(1, strMerchId, "~") > 0)
{
    vntPF = Strings.Split(strMerchId, "~");
    strPFUser = vntPF(INT_PF_USER);
    strPFVendor = vntPF(INT_PF_VENDOR);
}
else
{
    strPFUser = strMerchId;
    strPFVendor = strMerchId;
}

在这里,如何声明 Dim vntPayFlow As Variant

2 个答案:

答案 0 :(得分:3)

似乎为了回答你的问题我们必须做一个反向engeneering ...看起来你只想拆分 strMerchId,如果包含2个,则应分别分配,如果只有一个,则应将此单个项目分配给strPFUserstrPFVendor

// Assume that strMerchId is not null
String[] vntPF = strMerchId.Split('~'); // no variant, just an array

if (vntPF.Length == 2) { // Or >= 2
  strPFUser = vntPF[0];
  strPFVendor = vntPF[1];
}
else {
  strPFUser = strMerchId;
  strPFVendor = strMerchId;
}

答案 1 :(得分:2)

根据评论,您根本不需要使用Variant。使用String[],因为它也在VB.NET中。也可以使用VB.NET而不是VB,例如String.Split而不是SplitString.IndexOf而不是InStr。然后它更容易转换,因为它们都使用.NET。

所以喜欢:

const int INT_PF_USER = 0;
const int INT_PF_VENDOR = 1;
string strPFUser = strMerchId;   // assignment replaces the else of the following if
string strPFVendor = strMerchId; // assignment replaces the else of the following if
string[] vntPF;
// if you want to know if it is contained you can also use strMerchId.Contains("~")
int indexOfTilde = strMerchId.IndexOf('~');
if(indexOfTilde >= 0) // index starts at 0
{
    vntPF = strMerchId.Split('~');
    strPFUser = vntPF[INT_PF_USER];
    strPFVendor = vntPF[INT_PF_VENDOR];
}