我有一個關于公共和靜態方法的問題。我是 C# 編碼新手,我知道公共方法只能使用物件訪問。但是,可以在沒有類物件的情況下訪問靜態方法。但是使用公共方法有什么意義呢?為什么不總是使用靜態方法?
uj5u.com熱心網友回復:
在public與static關鍵字無關。
你可以有一個public static方法。公共意味著該方法(或其他類成員(例如,屬性、欄位、委托、列舉、內部類))可供屬于另一個類的代碼使用(替代方法是private,internal以及一些組合)。
該static關鍵字表示,獲得該成員不需要類的實體。在某些方面,您可以認為static成員屬于類,而非靜態成員屬于類的實體。VB 語言強調這個比喻,使用Shared代替static來描述靜態成員。
使用非靜態成員有很大的優勢(查找封裝- 這是一個很好的面試流行語)。面向物件的思維模式是,一個物件代表一個資料結構(C# 中的一個類或一個結構)以及可以在該資料結構上執行的操作。這些操作是類的非靜態方法。
uj5u.com熱心網友回復:
我認為 Flydog57 的回答要完整得多。在我的回答中,我將添加代碼示例,希望讓它更容易理解。
公共- 訪問修飾符,它確定可以從何處訪問您的代碼(方法/類/等)。Public 沒有任何限制,因此您基本上可以從任何地方訪問您的代碼。另一方面,如果一個方法或屬性或其他東西是私有的,您只能從它所屬的類中訪問它。還有其他訪問修飾符,請查看此處。
靜態 - 靜態是一個修飾符關鍵字,它決定了你的方法、屬性等應該使用類的物件訪問還是應該使用類名直接訪問。
在下面的代碼中,添加是靜態的,但減法不是靜態的。因此,我們只能使用物件訪問減法。為了訪問 Add,我們需要使用類名“Math.AddAdd(5, 4)”。注意:輸出在注釋中給出。
class Math
{
public static int Add(int a, int b)
{
return a b;
}
public int Subtraction(int a, int b)
{
return a - b;
}
}
class Program
{
static void Main(string[] args)
{
Math math = new Math();
Console.WriteLine(math.Subtraction(10,4)); // 6
Console.WriteLine(math.Add(5, 4)); // Error CS0176 Member 'Math.Add(int, int)' cannot be accessed with an instance reference;
}
}
現在,如果我們洗掉公共訪問修飾符。我們得到以下錯誤。因為這些方法不再可以從類的外部訪問。查看此處以查看不同型別的默認訪問修飾符。
class Math
{
static int Add(int a, int b)
{
return a b;
}
int Subtraction(int a, int b)
{
return a - b;
}
}
class Program
{
static void Main(string[] args)
{
Math math = new Math();
Console.WriteLine(math.Subtraction(5, 4)); // Error CS0122 'Math.Subtraction(int, int)' is inaccessible due to its protection level
Console.WriteLine(math.Add(5, 4)); // Error CS0122 'Math.Subtraction(int, int)' is inaccessible due to its protection level
}
}
你什么時候使用它們:這兩個都有很多用例。在下面的示例中,我使用靜態屬性 TotalStudent 來計算學生(物件)的總數。當我使用 Name 屬性來保留該特定物件獨有的資訊時。也像上面的數學示例 c# 和許多其他編程語言都有 Math 靜態類,它可以讓您進行求和、加法和其他操作。
class Student
{
public string Name { get; set; }
public static int TotalStudent { get; set; } = 0;
public Student(string name)
{
Name = name;
TotalStudent ;
}
}
class Program
{
static void Main(string[] args)
{
Student s1 = new Student("Bob");
Console.WriteLine(s1.Name); // Bob
Console.WriteLine(Student.TotalStudent); // 1
Student s2 = new Student("Alex");
Console.WriteLine(s2.Name); // Alex
Console.WriteLine(Student.TotalStudent); // 2
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/369801.html
上一篇:如何轉換RESTAPI回應
