[英]Event publish and subscribe through C# attributes
Can we do event publish and subscription through C# attributes being specified on Method or property?? 我们可以通过方法或属性上指定的C#属性来进行事件发布和订阅吗?
If Property is changed .. then we need to fire a event... 如果属性更改..那么我们需要触发一个事件...
[FirePropertyChangedEvent] SomeProperty [FirePropertyChangedEvent] SomeProperty
I've answered a similar question to this one, so ill copy my answer: 我已经回答了与此类似的问题,因此请复制我的答案:
lets say you are using a local "speed" variable, which you want updated every time the main "speed" variable is updated... 假设您使用的是本地“速度”变量,则每次主“速度”变量更新时都希望更新...
public class SpeedHolder
{
private float _speed;
public event Action<float> OnSpeedChange;
public float Speed
{
get { return _speed; }
set { SetSpeed(value); }
}
public SetSpeed(float value)
{
_speed = value;
if(OnSpeedChange != null)
OnSpeedChange(_speed);
}
}
now in every 'constructor' method of every script which uses a speed float variable, you need to add this line: SpeedHolder.OnSpeedChange += ChangeSpeed;
现在,在每个使用速度浮点变量的脚本的每个“构造函数”方法中,都需要添加以下行: SpeedHolder.OnSpeedChange += ChangeSpeed;
and have a method like this one: 并有一个像这样的方法:
public void ChangeSpeed(value)
{
speed = value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.