C#中的Get和Set方法通常用于封裝類的屬性,以便在訪問和修改屬性時執行某些操作。雖然Get和Set方法是基本的屬性訪問修飾符,但它們也可以具有高級用法,例如:
public class MyCollection<T>
{
private List<T> _items = new List<T>();
public T this[int index]
{
get { return _items[index]; }
set { _items[index] = value; }
}
}
public class MyClass
{
public int MyProperty { get; set; }
}
public static void SetProperty<T>(this T obj, Expression<Func<T, int>> property, int value)
{
var member = (MemberExpression)property.Body;
var propertyInfo = (PropertyInfo)member.Member;
propertyInfo.SetValue(obj, value);
}
public class MyClass
{
public delegate int Getter();
public delegate void Setter(int value);
private int _myProperty;
public MyClass(Getter getter, Setter setter)
{
_getter = getter;
_setter = setter;
}
public int MyProperty
{
get { return _getter(); }
set { _setter(value); }
}
}
public class MyBaseClass { }
public class MyClass<T> where T : MyBaseClass
{
public T MyProperty { get; set; }
}
public class MyAttribute : Attribute
{
public string MyProperty { get; set; }
}
[My(MyProperty = "Hello, World!")]
public class MyClass
{
public string MyProperty { get; set; }
}
這些高級用法可以幫助您更好地控制類的屬性訪問和修改行為,從而實現更靈活和可擴展的代碼。