using System;
using System.Collections.Generic;
namespace exercise_69
{
class Program {
{
public static void Main(string[] args)
{
List<int> numbers = new List<int>()。
//創建一個名為數字的串列。
while (true)
{
int input = Convert.ToInt32(Console.ReadLine() )。
if (input == -1)
{
break;
}
numbers.Add(input);
}
//ffill a list called numbers until user enter " -1 "
Console.WriteLine("從哪里")。
int lownum = Convert.ToInt32(Console.ReadLine() )。
//最低的數字得到列印。
Console.WriteLine("where to")。
int highnum = Convert.ToInt32(Console.ReadLine() )。
//highest number to get printed
foreach(int number in numbers)
{
if(lownum < number || highnum > number)
{
Console.WriteLine(numbers)。
} //trying to filter the numbers and print them .
}
}
}
}
blockquote
我遇到的問題是,當我運行該程式時,控制臺只是告訴我這一點 "System.Collections.Generic.List`1[System.Int32]" 所以我的問題是,我如何正確地過濾或洗掉串列中某一數值內的數字(而不是索引)
uj5u.com熱心網友回復:
控制臺只是告訴我這個 "System.Collections.Generic.List`1[System.Int32]"
。
這是因為你這樣做了:
這是因為你這樣做了。
Console.WriteLine(numbers)。
numbers是一個List<int>,它是一個完整的數字集合而不僅僅是一個數字。Console.WriteLine有許多變體("多載"),知道如何做所有不同種類的事情。它有一個大量的特定變體,用于數字、字串等,有一個變體就像一個 "萬能的"--它接受一個物件,這意味著它可以接受C#宇宙中的幾乎所有東西。如果你設法最終使用這個變體(多載),它唯一做的事情就是在你傳入的任何東西上呼叫ToString(),然后列印它得到的字串。
因為你傳入了一個List<int>,而Console.WriteLine沒有任何變數可以對List做任何具體的處理,這意味著你傳入的List會被WriteLine的萬能版本處理;"對傳入的東西呼叫ToString并列印結果"。因為List沒有一個非常具體或有趣的ToString(),它只是從object繼承了一個ToString()版本,這是C#中所有東西的最簡單根源。Object的ToString()并沒有什么作用--它只是回傳物件的型別,在本例中,它是一個 "System.Collections.Generic.List`1[System.Int32]"...這就是為什么你會在控制臺中看到你所看到的東西
現在你知道了為什么你的代碼要列印List的型別,因為你傳入的是一個List,你能看到如何改變它,使你傳入的是其他東西(比如,你想列印的實際數字)?
Console.WriteLine(numbers)。
^^^^^^^
this需要一些else - 你能出來什么?
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/308539.html
標籤:
