[英]C# - Getting the 3 lowest values in a List, measured by a public property of the objects within the List
[英]C# public list of objects
我正在從VB轉換為C#並努力研究如何訪問公共對象列表......
class Program
{
public List<players> myListOfPlayers = new List<players>();
static void Main(string[] args)
{
foreach(var player in myListOfPlayers)
{
}
}
class players
{
public string playerName { get; set; }
public string playerCountry { get; set; }
}
}
在我的主模塊中,我無法訪問“myListOfPlayers”。
按照設計,您無法從靜態成員訪問非靜態成員
從MSDN Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
你需要靜態修改器
public static List<players> myListOfPlayers = new List<players>();
您需要一個Program
類的實例:
static void Main(string[] args)
{
Program p = new Program(); // p is the instance.
foreach(var player in p.myListOfPlayers)
{
}
}
這相當於:
Dim p As New Program
或者,您可以將myListOfPlayers
靜態。
作為附加注釋,您應該嘗試遵循正確的命名約定,例如: C#
類應該首字母大寫。 players
應該是Players
。
您無法從靜態上下文訪問非靜態上下文。 因此,嘗試訪問構造函數中的列表。
class Program
{
public List<players> myListOfPlayers = new List<players>();
public Program(){
foreach(var player in myListOfPlayers)
{
}
}
static void Main(string[] args)
{
new Program();
}
class players
{
public string playerName { get; set; }
public string playerCountry { get; set; }
}
}
變量myListOfPlayer
不是靜態的,因此它只存在於類的實例的上下文中。 由於main方法是靜態的,因此它不存在於實例的上下文中,因此它不能“看到”實例成員
您需要使myListOfPlayer
靜態,以便您可以從實例方法訪問它。
public static List<players> myListOfPlayers = new List<players>();
class Program
{
static void Main(string[] args)
{
List<players> myListOfPlayers = new List<players>();
foreach (var player in myListOfPlayers)
{
}
}
}
class players
{
public string playerName { get; set; }
public string playerCountry { get; set; }
}
嘗試上面的代碼,它應該工作。 如果您有任何問題,請告訴我
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.