任何人都可以告诉我如何存储和返回字符串列表。如何返回字符串列表中的c#
有人问我,是因为我已经写了返回字符串的集合函数,我
要准备一个COM对于一个需要消耗的是COM(获取返回的列表)在
vC++其中我可以使用该字符串列表扩展一些功能。
我希望thius将会一目了然......
由于提前
任何人都可以告诉我如何存储和返回字符串列表。如何返回字符串列表中的c#
有人问我,是因为我已经写了返回字符串的集合函数,我
要准备一个COM对于一个需要消耗的是COM(获取返回的列表)在
vC++其中我可以使用该字符串列表扩展一些功能。
我希望thius将会一目了然......
由于提前
List<string>或字符串[]是最好的选择。
这里是返回字符串列表的样品的方法:
public static List<string> GetCities()
{
List<string> cities = new List<string>();
cities.Add("Istanbul");
cities.Add("Athens");
cities.Add("Sofia");
return cities;
}
可以存储字符串作为阵列的固定列表:
string[] myStrings = {"Hello", "World"};
或动态列表作为List<string>
:
List<string> myStrings = new List<string>();
myStrings.Add("Hello");
myStrings.Add("World");
在C#中,您可以简单地返回List<string>
,但您可能想要ret嗯IEnumerable<string>
相反,因为它允许惰性评估。
昨天你问过如何通过COM interop来做到这一点!为什么退一步?
How to return a collection of strings from C# to C++ via COM interop
public static IList<string> GetStrings()
{
foreach(var item in GetStringItems())
yield return item;
}
有很多方法来表示字符串在.NET中的列表,列表<串>是最光滑的。但是,你不能这样回COM,因为:
COM不理解.NET泛型
的FxCop会告诉你,这是不好的做法,返回内部实现的东西(名单)而不是抽象接口(IList/IEnumerable)。
除非你想进入真正可怕的变异的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; }
}
(见http://msdn.microsoft.com/en-us/library/bb352856.aspx for more help)
请提供更多资讯 - 商店永久奥德只是“建立一个列表/返回该列表“? “返回”就像方法的结果一样? – 2009-06-24 07:18:33
真的不清楚你的意思;要么这是简单的,要么是看似深刻的,取决于你的意图... – 2009-06-24 07:18:36
更多输入请, 你想实现什么? 伪代码可能有帮助 – 2009-06-24 07:18:49