使用属性触发属性的获取和设置
本文关键字:属性 获取 设置 | 更新日期: 2025-01-25 11:00:28
我需要构建一个属性,该属性将覆盖属性的getter和setter。更清楚地说,以下是它目前的工作方式,以及它应该如何使用属性(结果应该是相同的)。
旧版本:
public class A
{
private Handle _handle;
public String StringProp
{
get {
return _handle.GetProperty(PropId.StringProp);
}
set {
_handle.SetProperty(PropId.StringProp, value);
}
}
public int IntProp
{
get {
return _handle.GetProperty(PropId.IntProp);
}
set {
_handle.SetProperty(PropId.IntProp, value);
}
}
}
新版本:
public class A
{
private Handle _handle;
[HandleProperty(PropId.StringProp)]
public String StringProp { get; set; }
[HandleProperty(PropId.IntProp)]
public int IntProp { get; set; }
}
属性HandleProperty
应该是已知的,以便将getter和setter链接到_handle.GetProperty
和_handle.SetProperty
。
我创建了两个枚举,一个枚举中的一些字段使用属性映射到另一个枚举字段。我想你可以做这样的事。。。
[AttributeUsage(AttributeTargets.Field)]
public sealed class MapsToAttribute : Attribute
{
private string Text;
public string MapsToText
{
get
{
return Text;
}
}
public MapsToAttribute(string mapsToText)
{
Text = mapsToText;
}
public override string ToString()
{
return Text;
}
}