[英]How to use properties in C#
創建Class1
的對象並嘗試使用Main運行此屬性時收到的錯誤是:
“錯誤1不可發音的成員'ConsoleApplication1.Class1.X_ValueProperty'不能像方法一樣使用。C:\\ Users \\ Qosmio \\ AppData \\ Local \\ Temporary Projects \\ ConsoleApplication1 \\ Program.cs 14 15 ConsoleApplication1”
我完全理解此錯誤。 IE,您不能像運行方法一樣運行屬性,但是看來我從中了解到的視頻的演示者是可以做到的。 (圍繞1:20標記。)
在Main方法中,似乎他先調用對象,然后調用屬性,然后在出現錯誤時輸入一個值。
誰能識別我在做什么錯?
class Class1
{
int x;
public int X_ValueProperty
{
set {
if (value <= 0)
{
throw new Exception("Value cannot be zero or less than zero.");
}
this.x = value;
}
get
{
return this.x;
}
}
}
這是錯誤的來源:
class Program
{
static void Main(string[] args)
{
Class1 z= new Class1();
//Error--> z.X_ValueProperty();
}
}
您必須像下面這樣調用該屬性:
Class1 cls = new Class1();
cls.X_ValueProperty();
請注意其屬性而不是方法,您可以設置或獲取類的屬性的值。 請先正確了解屬性 。
您可以設置\\獲取像這樣的值:
cls.X_ValueProperty = 25;
int x = cls.X_ValueProperty;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.