这个问题搞砸了.
见底部
在ResultsB中如何访问List?
public class ResultsB : List<ResultB>
{
public string Methods
{
get
{
// what I want is
return string.Join(", ", this);
// and have this be List<ResultB>
// this fails
// it returns "PuzzleBinarySearchWeighted.Program+ResultB, PuzzleBinarySearchWeighted.Program+ResultB"
// I just get information about the object
// this fails also - same thing information about the object
//return string.Join(", ", this.GetEnumerator());
}
}
public void testEnum()
{
// this works
foreach (ResultB resultB in this)
{
Debug.WriteLine(resultB.MethodsString);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在外部我可以这样做 -
ResultsB resultsB = new ResultsB();
resultsB.Add(new ResultB(1, "a:b"));
resultsB.Add(new ResultB(2, "c:b"));
Run Code Online (Sandbox Code Playgroud)
我只是看着这个错误
我需要一个iEnumerable来自所有列表
我无法删除作为答案已经投票
对不起 - 我VTC并要求你做同样的事情
public string Methods
{
get
{
return string.Join(", ", this.MethodsAll);
}
}
public HashSet<string> MethodsAll
{
get
{
HashSet<string> hs = new HashSet<string>();
foreach (ResultB resultB in this)
{
foreach (string s in resultB.Methods)
{
hs.Add(s);
}
}
return hs;
}
}
Run Code Online (Sandbox Code Playgroud)
隐含着this.
例如,调用Add如下Add("hello world")隐含的是this.Add("hello world"):
public class CustomListOfStrings : List<string>
{
// ...
private void DoStuff()
{
Add("Whatever");
}
}
Run Code Online (Sandbox Code Playgroud)
@Paparazzi评论说:
我应该更清楚我需要一个foreach
this 救援关键词!
foreach(ResultB result in this)
{
}
Run Code Online (Sandbox Code Playgroud)
string.Join直接使用OP编辑了这个问题,并说要使用string.Join如下:
string.Join(", ", this).
string.Join您可以使用的重载是string.Join(string,?IEnumerable<T>),它将调用Object.ToString给定序列中的每个对象(即IEnumerable<T>).所以你需要Object.ToString在结果类中提供一个重写方法(你可以在Reference Source上查看string.Join):
public class ResultB
{
public override string ToString()
{
// You need to provide what would be a string representation
// of ResultB
return "Who knows what you want to return here";
}
}
Run Code Online (Sandbox Code Playgroud)
...并且您的代码将按预期工作!