![](/img/trans.png)
[英]Clarification Help Needed - C# / OOP / Inheritance / Polymorphism / Multiple Inheritance
[英]Clarification on C# OOP
從基本看一下在main方法中運行的測試器類,我們已經獲得了構造面向對象類的任務。
using System;
using school;
namespace testschool{
public class Tester {
static void Main(){
Faculty scienceFac=University.createFaculty("Science");
Department compSciDept= scienceFac.openNewDepartment("Computer Science");
Department physicsDept= scienceFac.openNewDepartment("Physics");
Console.WriteLine(Object.ReferenceEquals(
scienceFac, physicsDept.Faculty)); //expected to return scienceFac object
Console.WriteLine(University.numberOfFaculties());
//..... MORE CODE
我認為他使代碼盡可能地令人困惑,並且確實變得令人困惑。 我剛剛開始,但已經陷入困境,但是到目前為止,這是我所擁有的。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testschool
{
class University
{
List<Faculty> all_faculty = new List<Faculty>();
public Faculty createFaculty(string faculty_name)
{
Faculty new_faculty = new Faculty(faculty_name);
all_faculty.Add(new_faculty);
return new_faculty;
}
public int numberOfFaculties()
{
return all_faculty.Count;
}
}
class Faculty
{
string faculty_name;
List<Department> all_departments = new List<Department>();
public Faculty(string faculty_name)
{
this.faculty_name = faculty_name;
}
public Department openNewDepartment(string department_name)
{
Department new_department = new Department(department_name, this);
all_departments.Add(new_department);
return new_department;
}
}
class Department
{
string department_name;
Faculty parent_faculty;
public Department(string department_name, Faculty faculty)
{
this.department_name = department_name;
parent_faculty = faculty;
}
public Faculty Faculty
{
get { return parent_faculty; }
}
}
}
到目前為止,我有兩個問題:
第一:這行代碼: Faculty scienceFac = University.createFaculty("Science");
似乎只是在沒有對象引用的情況下立即調用大學。 我宣布大學為一類,因為它內部似乎也有.createFaculty(“ Science”)和.numberOfFaculties()之類的方法。 那可能是個錯誤嗎? 還是大學實際上是一個名稱空間或其他具有自己方法的東西?
第二:一所大學有系,一所大學有系,最終到了有學生和課程的地步。 從代碼中可以看出,我使用了列表,但是我們沒有涉及到列表。 僅數組(是的,我知道列表也是數組,但是我只想堅持使用數組)。 是否可以在不聲明預定義大小的情況下使用數組? (我總是可以將大小設置為999之類的大字,但實際上並不實用)
問題的具體答案:
University.createFaculty()
是靜態方法。 使用類型名稱而不是實例來調用它。
要創建數組實例,必須指定大小。 但是變量本身是在沒有任何大小信息的情況下聲明的。
我認為這可以解決您的具體要求。 當然,在教育環境中,如果有空的話,最好與您的老師協商。 這可以幫助您獲得更適合該課程的答案,以及老師希望您學習的內容,還可以幫助老師了解每個學生在理解課程和作業方面所處的位置。
1-正如@Peter Duniho提到的那樣, University.CreateFaculty()
是靜態方法
public class University
{
public static void CreateFaculty()
{
// a static method declared inside a class can be called without creating an instance of the object
}
}
2-要調整數組的大小,可以執行以下操作
int[] data=new int[2];
data[0]=1;
data[2]=2;
data=ResizeData(data,3); // this function will return new array with array with length=5
public int[] ResizeData(int[] data,int number)
{
int[] newArray=new int[number]();
for(int i=0;i<data.Length;i++) // copy the data from dataArray to the newArray
newArray[i]=data[i];
return newArray;
}
希望這個能對您有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.