【问题标题】:C# equivalent of Visual Basic Code with CTypeC# 等效于具有 CType 的 Visual Basic 代码
【发布时间】:2015-03-04 11:47:43
【问题描述】:

我知道我可以在 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!

这是一个结构体(来自 Translator 类)

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 代码,尤其是后面的点符号?

【问题讨论】:

标签: vb.net ctype


【解决方案1】:

你已经翻译了这个:

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.Trim 是对 String.Trim 的调用。在 C# 中,方法调用需要括号,因此应为:

Row.TypeName.Trim()

【讨论】:

  • 是的,拥有一个强类型集合将使其无需任何转换即可工作。
猜你喜欢
  • 2019-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多