[英]Translate from VB to C# for loop
I used a popular online code converter to go from VB to C# and the C# is not working on this for loop. 我使用了一个流行的在线代码转换器,将其从VB转换为C#,而C#对此for循环不起作用。 Can any C# experts see the problem?
任何C#专家都能看到问题吗?
More specifically intellisense is telling me that CustomerRoles()
cannot be used like a method. 更具体地说,intellisense告诉我不能像方法一样使用
CustomerRoles()
。 It works fine in VB. 在VB中工作正常。
VB: VB:
Dim Roles As New List(Of String)
For x As Integer = 0 To EngineContext.Current.Resolve(Of IWorkContext)().CurrentCustomer.CustomerRoles().Count - 1
Roles.Add(EngineContext.Current.Resolve(Of IWorkContext)().CurrentCustomer.CustomerRoles(x).Name)
ddlRoles.Items.Add(EngineContext.Current.Resolve(Of IWorkContext)().CurrentCustomer.CustomerRoles(x).Name)
Next
C# (this is not working) : C#(这不起作用):
List<string> Roles = new List<string>();
for (int x = 0; x <= EngineContext.Current.Resolve<IWorkContext>().CurrentCustomer.CustomerRoles().Count - 1; x++) {
Roles.Add(EngineContext.Current.Resolve<IWorkContext>().CurrentCustomer.CustomerRoles(x).Name);
ddlRoles.Items.Add(EngineContext.Current.Resolve<IWorkContext>().CurrentCustomer.CustomerRoles(x).Name);
}
Replace 更换
CustomerRoles(x).Name
with 与
CustomerRoles[x].Name
You access the indexer of arrays (or lists) with squared brackets instead of paranthesis in C#. 您可以使用方括号而不是C#中的括号访问数组(或列表)的索引器。
If it's not a collection but a property or field you just have to remove the paranthesis: 如果它不是一个集合,而是一个属性或字段,则只需要删除该括号即可:
CustomerRoles.Name
If that doesn't work(for whatever reason) you can try Enumerable.ElementAt
: 如果由于某种原因这不起作用,您可以尝试
Enumerable.ElementAt
:
CustomerRoles.ElementAt(x).Name
That works with any kind of IEnumerable<T>
even if it doesn't implement IList<T>
(needed for the indexer). 即使它不实现
IList<T>
(索引器需要),它也可以与任何IEnumerable<T>
。
Try this: 尝试这个:
C#(this is not working)
List<string> Roles = new List<string>();
for (int x = 0; x <= EngineContext.Current.Resolve<IWorkContext>().CurrentCustomer.CustomerRoles.Count - 1; x++) {
Roles.Add(EngineContext.Current.Resolve<IWorkContext>().CurrentCustomer.CustomerRoles[x].Name);
ddlRoles.Items.Add(EngineContext.Current.Resolve<IWorkContext>().CurrentCustomer.CustomerRoles[x].Name);
}
Ok i've tried in VB CustomerRoles(x)
is equivalent to CustomerRoles.ElementAtOrDefault(x);
好的,我在VB中尝试过
CustomerRoles(x)
等同于CustomerRoles.ElementAtOrDefault(x);
in c#. 在C#中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.