C# 我如何从班级返回列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/586116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i return List from Class
提问by Penguen
class Program
{
static void Main(string[] args)
{
mylist myitems1 = new mylist("Yusuf","Karatoprak");
SelectedItemsList slist = new SelectedItemsList();
slist.Items.Add(myitems1);
foreach( object o in slist.Items)
Console.Write(o.ToString()+"\n");
Console.ReadKey();
}
}
public class mylist
{
private string Ad;
private string SoyAd;
public mylist(string ad, string soyad)
{
Ad = ad;
SoyAd = soyad;
}
public override string ToString()
{
return "Ad:" + this.Ad;
}
}
public class SelectedItemsList
{
public List Items;
public SelectedItemsList()
{
Items = new List<mylist>();
}
}</code></pre>
i want to return an arraylist or list form mylist class but how? return this.Ad, also retun this.SoayAd etch.
Please look ToString() procedure: it is return Ad but i want to return Ad also SoyAd together. Not only Ad ,but also Ad,SoyAd in a List.
我想从 mylist 类返回一个数组列表或列表,但是如何返回?返回 this.Ad,也返回 this.SoayAd 蚀刻。请查看 ToString() 过程:它是返回 Ad 但我想同时返回 Ad 和 SoyAd。不仅是 Ad ,还有 Ad, SoyAd 在列表中。
回答by Jon Skeet
Your question is very unclear, but if you mean you want mylist to have a method which returns a list containing Ad and SoyAd, then just do it like this:
你的问题很不清楚,但如果你的意思是你想让 mylist 有一个方法来返回一个包含 Ad 和 SoyAd 的列表,那么就这样做:
// This could be a property
public IList<string> GetAds()
{
List<string> ret = new List<string>();
ret.Add(Ad);
ret.Add(SoyAd);
return ret;
}
If you can make do with IEnumerable<string>you could use an iterator block:
如果你可以使用IEnumerable<string>你可以使用迭代器块:
// This could be a property
public IEnumerable<string> GetAds()
{
yield return Ad;
yield return SoyAd;
}
回答by luiscubal
To return an ArrayList or List, just use "public List someFunction()" or "public ArrayList someFunction()". If this is not what you want, please rephrase your question.
要返回 ArrayList 或 List,只需使用“public List someFunction()”或“public ArrayList someFunction()”。如果这不是您想要的,请重新表述您的问题。
回答by abatishchev
To return list only of ador soyadkeep it independent lists, filled on adding
仅返回列表ad或soyad保持独立列表,在添加时填写

