在派生List<>的类中,如何访问列表

时间:2016-12-18 21:23:53

标签: c# .net

这个问题搞砸了 见底部

在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);
        }
    }
}

在外部,我可以这样做 -

 ResultsB resultsB = new ResultsB();
 resultsB.Add(new ResultB(1, "a:b"));
 resultsB.Add(new ResultB(2, "c:b"));

我只是看着这个错误的 我需要一个来自所有列表的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;
    }
}

1 个答案:

答案 0 :(得分:5)

隐含this

例如,按以下Add调用Add("hello world")隐含this.Add("hello world")

public class CustomListOfStrings : List<string>
{
      // ...
      private void DoStuff() 
      {
            Add("Whatever");
      }
}

@Paparazzi评论说:

  

我应该更清楚我需要一个foreach

救援的

this关键字!

foreach(ResultB result in this)
{

}

OP希望直接使用string.Join

OP已对此问题进行了编辑,并表示希望使用string.Join,如下所示:

string.Join(", ", this)

您可以使用的string.Join重载是string.Join(string, IEnumerable<T>),它会在给定序列中找到的每个对象上调用Object.ToString(即IEnumerable<T>)。因此,您需要在结果类中提供重写的Object.ToString方法(可以在Reference Source for 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";
     }
}

...您的代码将按预期运行!