任何人都可以告诉我如何编写C#可枚举类,以便Excel VBA中的"for each"构造正常工作吗?我尝试了一个名为People的测试类,它实现了IEnumerable并包含一个Person对象数组."foreach"构造在C#中运行良好,但在VBA中我只能循环使用老式的方式.
这个VBA代码工作得很好:
Dim P As Person
Dim PP As New People
For i = 0 To PP.Count - 1
Set P = PP(i)
Debug.Print P.firstName + " " + P.lastName
Next i
Run Code Online (Sandbox Code Playgroud)
但这在运行时失败("对象不支持此属性或方法"):
For Each P In PP
Debug.Print P.firstName + " " + P.lastName
Next P
Run Code Online (Sandbox Code Playgroud)
下面是C#代码(在VS 2008中可见的已编译COM,用于Excel VBA - Office 2010):
using System;
using System.Collections;
using System.Runtime.InteropServices;
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}
public string …Run Code Online (Sandbox Code Playgroud)