如何使用字符串委托订阅的2种方法 [英] How to use string delegate subscribed to 2 methods
问题描述
我有2个C#类,其中一个有一个字符串委托,另一个则向该委托订阅了一个函数.
I have 2 C# classes one of them has a string delegate and the other subscribes an function to that delegate.
我的问题是我想从委托中组合两个被调用的字符串函数,而不是随机选择它们之间的返回值
My question is I want to combine the two called string functions from the delegate instead of choosing the return value between them randomly
delgatesystem.cs:
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:
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个游戏对象.
note: the delgatesave.cs is attached to 2 gameobjects.
推荐答案
首先,使用非无效委托创建事件是一种反模式.事件通常与可能有更多订阅者一起使用.
First of all, creating events with non-void delegates is an antipattern. Events are typically used with potentially more subscribers.
如果有多个订阅者调用了一个非无效的多播委托,则总是返回最后一个订阅方法的返回值.
If a non-void multicast delegate is invoked with multiple subscribers, always the return value of the last subscribed method is returned.
但是毕竟,您可以执行以下操作:
But after all you can do something like this:
string[] objectNames = MyEvent.GetInvocationList().Cast<MyDelegate>().Select(del => del()).ToArray();
但是,更好的解决方案是使用更多常规事件:
However, a better solution would be to use more conventional events:
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);
发票:
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);
}
这篇关于如何使用字符串委托订阅的2种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!