我有2个C#类,其中一个有一个字符串委托,另一个向该委托订阅一个函数。
我的问题是我想要从委托中组合两个被调用的字符串函数,而不是随机选择它们之间的返回值
delgatesystem.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class delegatesystem : MonoBehaviour {
public delegate string MyDelegate();
public static event MyDelegate MyEvent;
string GameObjectsNames = "";
void Update ()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (MyEvent != null)
{
GameObjectsNames += MyEvent();
}
}
}
}
delegatesave.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class delegatesave : MonoBehaviour {
void Start ()
{
delegatesystem.MyEvent += DelegateFunction;
}
string DelegateFunction()
{
return gameObject.name;
}
}
注意: delgatesave.cs附加到2个游戏对象。
答案 0 :(得分:2)
首先,使用非void委托创建事件是反模式。事件通常与潜在的更多订阅者一起使用。
如果使用多个订阅者调用非void多播委托,则始终返回最后一个订阅方法的返回值。
但毕竟你可以这样做:
string[] objectNames = MyEvent.GetInvocationList().Cast<MyDelegate>().Select(del => del()).ToArray();
但是,更好的解决方案是使用更多传统事件:
public class PopulateNamesEventArgs : EventArgs
{
private List<string> names = new List<string>();
public string[] Names => names.ToArray();
public void AddName(string name) => names.Add(name);
}
然后在你的班上:
public event EventHandler<PopulateNamesEventArgs> MyEvent;
protected virtual void OnMyEvent(PopulateNamesEventArgs e) => MyEvent?.Invoke(this, e);
Invokation:
var e = new PopulateNamesEventArgs();
OnMyEvent(e);
string[] objectNames = e.Names; // the result is now populated by the subscribers
订阅:
void Start()
{
delegatesystem.MyEvent += DelegateFunction;
}
void DelegateFunction(object sender, PopulateNamesEventArgs e)
{
e.AddName(gameObject.name);
}