在C#中,使用屬性(get和set)可以方便地獲取和設置類的屬性值。為了避免錯誤,請遵循以下準則:
public class MyClass
{
private int _myProperty;
public int MyProperty
{
get { return _myProperty; }
set { _myProperty = value; }
}
}
public class MyClass
{
private int _myProperty;
public int MyProperty
{
get { return _myProperty; }
set
{
if (value >= 0 && value <= 100)
{
_myProperty = value;
}
else
{
throw new ArgumentOutOfRangeException(nameof(value), "Value must be between 0 and 100.");
}
}
}
}
[Required]
、[Range]
等屬性來驗證屬性值。例如:public class MyClass
{
[Required]
[Range(0, 100)]
public int MyProperty { get; set; }
}
public class MyClass
{
public int MyProperty { get; set; } = 0;
}
public class MyClass
{
private int _myProperty;
public int MyProperty
{
get { return _myProperty; }
set
{
_myProperty = value;
OnPropertyChanged(nameof(MyProperty));
}
}
public void SetMyProperty(int value)
{
if (value >= 0 && value <= 100)
{
_myProperty = value;
OnPropertyChanged(nameof(MyProperty));
}
else
{
throw new ArgumentOutOfRangeException(nameof(value), "Value must be between 0 and 100.");
}
}
}
遵循這些準則可以幫助您避免在使用C#屬性時出現錯誤。