有人能告诉我如何存储和返回字符串列表吗?
我问这个问题是因为我编写了一个返回字符串集合的函数,并且我想为它准备一个COM,并需要在VC++中使用它来获取返回的字符串列表,以便我可以使用该字符串列表扩展一些功能。我希望这清楚明白。
有人能告诉我如何存储和返回字符串列表吗?
我问这个问题是因为我编写了一个返回字符串集合的函数,并且我想为它准备一个COM,并需要在VC++中使用它来获取返回的字符串列表,以便我可以使用该字符串列表扩展一些功能。我希望这清楚明白。
List<string>或string[]是最佳选择。
这是一个返回字符串列表的示例方法:
public static List<string> GetCities()
{
List<string> cities = new List<string>();
cities.Add("Istanbul");
cities.Add("Athens");
cities.Add("Sofia");
return cities;
}
List<string>
,但你可能希望返回IEnumerable<string>
,因为它允许进行惰性评估。string[] myStrings = {"Hello", "World"};
或者一个动态列表,例如List<string>
:
List<string> myStrings = new List<string>();
myStrings.Add("Hello");
myStrings.Add("World");
在.NET中,表示字符串列表的方式有很多种,List<string>是最流畅的一种。然而,你不能将其返回给COM,因为:
COM不理解.NET泛型
FxCop会告诉你,返回某个东西(List)的内部实现而不是抽象接口(IList / IEnumerable)是不好的做法。
除非你想涉及到非常可怕的Variant SafeArray对象(不建议这样做),否则你需要创建一个“集合”对象,以便你的COM客户端可以枚举字符串。
类似于这样(未编译 - 这只是一个示例,让你开始):
[COMVisible(true)]
public class CollectionOfStrings
{
IEnumerator<string> m_enum;
int m_count;
public CollectionOfStrings(IEnumerable<string> list)
{
m_enum = list.GetEnumerator();
m_count = list.Count;
}
public int HowMany() { return m_count; }
public bool MoveNext() { return m_enum.MoveNext(); }
public string GetCurrent() { return m_enum.Current; }
}
昨天你问了如何通过COM互操作完成这个任务!为什么要倒退呢?
public static IList<string> GetStrings()
{
foreach( var item in GetStringItems())
yield return item;
}