[英]C# How can I access a method that contains a foreach loop in my main?
我想要這樣,以便拆分姓名列表,然后拆分名字和姓氏,以便對每個人的名字和姓氏對進行操作。 因此,我有一個用“;”分隔的名稱列表。 將其拆分為一個數組在另一個類中,我獲得了該數組,並使用foreach將字符串中的char拆分為',',並給了我名字和姓氏。
我想知道如何將最后一個操作稱為主體,這樣我的名字和姓氏最終都可以各自執行自己的操作。
謝謝
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
pairInName funOperations = new pairInName();
//I'd like to have the method from 'pairInName' to have the split list ',' (from the split list ';')
//How can I run it so that it carries out the operation in my main()?
//eventually, I'd like it so that it carries out a method in my main for each pair of first and last name, for each name in the list
Console.WriteLine();
Console.ReadLine();
}
}
public class namesList
{
public static string listOfNames = (
"Tyrion,Lannister;" +
"Euron,GreyJoy;" +
"Davos,Seaworth;" +
"Lord,Varys;" +
"Samwell,Tarly;"
);
public static string[] splitListOfNames = listOfNames.Split(';');
}
public class pairInName
{
static void myOperations()
{
foreach (string champName in namesList.splitListOfNames)
{
string[] splitChampName = champName.Split(',');
}
}
}
}
標記為static的方法,如果還將訪問修飾符從private
(不填充任何修飾符時的默認值)更改為public
,則可以直接訪問它。
pairInName.myOperations();
備注:您的完整結構不是非常面向對象,您應該考慮使用更接近數據上下文實際性質的類和方法來重構設計。
創建Character
實體將是一個好的開始
public class Character
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public Character(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
將您的myOperations()標記為public,然后可以使用“ pairInName.myOperations();” 從主要方法看。
public class pairInName
{
string[] splitChampName;
public static void myOperations()
{
foreach (string champName in namesList.splitListOfNames)
{
splitChampName = champName.Split(',');
}
}
public string[] getSplitResult
{
get { return splitChampName; }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.