在设置或获取属性之前,应该执行一个方法,这在编译时是不知道的?是否可以将方法添加为运行时?
public string MyName
{
get
{
//A Methode should called here
return m_ASD;
}
set
{
//A Methode should called here
m_ASD = value;
}
}
在设置或获取属性之前,应该执行一个方法,这在编译时是不知道的?是否可以将方法添加为运行时?
public string MyName
{
get
{
//A Methode should called here
return m_ASD;
}
set
{
//A Methode should called here
m_ASD = value;
}
}
最简单的解决方案是提供可以在运行时设置的钩子:
public Action OnMyNameSet { get; set; }
public Action OnMyNameGet { get; set; }
public string MyName
{
get
{
if (OnMyNameGet != null) { OnMyNameGet(); }
return m_ASD;
}
set
{
if (OnMyNameSet != null) { OnMyNameSet(); }
m_ASD = value;
}
}
用法:
MyClass c = new MyClass();
c.OnMyNameSet = NameOfSomeMethod;
c.MyName = ...; // also executes NameOfSomeMethod();
或者,您可以创建消费者可以附加到的事件。这就是钩子通常在 .NET 框架中实现的方式。
public event EventHandler OnMyNameSet;
public event EventHandler OnMyNameGet;
public string MyName
{
get
{
if (OnMyNameGet != null) { OnMyNameGet(this, EventArgs.Empty); }
return m_ASD;
}
set
{
if (OnMyNameSet != null) { OnMyNameSet(this, EventArgs.Empty); }
m_ASD = value;
}
}
用法类似;但是请注意,使用 of+=
代替=
:
MyClass c = new MyClass();
c.OnMyNameSet += NameOfSomeMethod;
c.MyName = ...; // also executes NameOfSomeMethod(sender, eventArgs);