在设置或获取属性之前,应该执行一个在编译时未知的方法?是否可以将方法添加为运行时?
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;
}
}
用法类似;但是,请注意,使用+=
而不是=
:
MyClass c = new MyClass();
c.OnMyNameSet += NameOfSomeMethod;
c.MyName = ...; // also executes NameOfSomeMethod(sender, eventArgs);