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; }
}
这些高级用法可以帮助您更好地控制类的属性访问和修改行为,从而实现更灵活和可扩展的代码。