C#相当于Visual Basic Code和CType

时间:2015-01-06 18:36:02

标签: vb.net ctype

我知道我可以使用符号显式转换C#中的类型:(Type)Object 我正在将Visual Basic代码翻译为C#。

VB代码:

TempTrans(j) = CType(FillTranslator.IndxLanguage.Item(j), Translator.IndxLangauges.IndxTranslation).Translations.Item(Row.Name.Trim) //This is the line I need help with!

这是一个结构(来自翻译类)

Structure IndxLangauges
     Public IndxLanguage As Collection
     Structure IndxTranslation
           Public Language As Integer
           Public Name As String
           Public Translations As Collection
     End Structure
End Structure

此外:

Private Shared FillTranslator As Translator.IndxLangauges

在C#中我有:

public struct IndxLanguages
{
    public System.Collections.Generic.List<string> IndxLanguage;
    public struct IndxTranslation
    {
        public int Language;
        public string Name;
        public System.Collections.Generic.List<string> Translations;
    };
};

private static Translator.IndxLanguages FillTranslator;
TempTrans[j] = ((Translator.IndxLanguages.IndxTranslation)FillTranslator.IndxLanguage[j]).Translations[Row.TypeName.Trim];  //Error here

我收到错误:无法将类型字符串转换为Translator.IndxLanguages.IndxTranslation


我不明白转换后直接代码中的内容(在VB中):.Translations.Item(Row.Name.Trim)

有人可以帮我理解VB中的CType代码,特别是关于后面的点符号吗?

1 个答案:

答案 0 :(得分:4)

你翻译了这个:

Public IndxLanguage As Collection

public System.Collections.Generic.List<string> IndxLanguage;

这是错误的,因为IndxLanguage似乎包含IndxTranslation类型的元素,而不是String类型的元素。

您有两种方法可以解决这个问题:使用完全相同的(legacy) type来翻译字面行:

public Microsoft.VisualBasic.Collection IndxLanguage;

或(首选)指定正确的项目类型:

public System.Collections.Generic.List<Translator.IndxLanguages.IndxTranslation> IndxLanguage;

这样,你甚至不需要演员。

注意:一些usings会大大提高代码的可读性。例如,前一行可以简化为:

public List<IndxTranslation> IndxLanguage;

注2:Row.TypeName.TrimString.Trim的调用。在C#中,方法调用需要括号,因此它应显示为:

Row.TypeName.Trim()