C# 我可以通过一个方法在事件中开火吗?
我试图使我的GetStringFromServer方法更抽象一些,因为我不想为我对服务器的所有不同调用创建相同的方法,结果总是一样的;一个json字符串C# 我可以通过一个方法在事件中开火吗?,c#,unity3d,C#,Unity3d,我试图使我的GetStringFromServer方法更抽象一些,因为我不想为我对服务器的所有不同调用创建相同的方法,结果总是一样的;一个json字符串 public delegate void GoogleServerResponse(string result); public static event GoogleServerResponse OnGoogleServerResponse; void Start () { print ("goin
public delegate void GoogleServerResponse(string result);
public static event GoogleServerResponse OnGoogleServerResponse;
void Start () {
print ("going to google...");
StartCoroutine( GetStringFromServer("http://google.com", OnGoogleServerResponse) );
}
IEnumerator GetStringFromServer(string url, Event e) {
WWW www = new WWW(url);
yield return www;
if( e != null )
e (www.text);
}
我想这可以通过URL触发传入事件,使我能够侦听事件,并为对我的Web服务器的不同调用(不是google ofc,但通常是“/getplayer”、“createnewgame”等)定义多个事件。如果无法传递
事件,应该尝试(代理/包装器)操作
IEnumerator GetStringFromServer(string url, Action<string> e) {
WWW www = new WWW(url);
yield return www;
if( e != null )
e (www.text);
}
只有当您试图传递另一个类(类之外)的事件时,不能传递事件这一事实才适用
如果您试图从定义事件的类中传递事件,没有人会阻止您这样做
例如,下面的工作对我来说
public delegate void GoogleServerResponse(string result);
public class PassEvent
{
public static event GoogleServerResponse OnGoogleServerResponse;
private void Start()
{
print("going to google...");
StartCoroutine(GetStringFromServer("http://google.com", OnGoogleServerResponse));
}
private void print(string p)
{
}
private void StartCoroutine(IEnumerator enumerator)
{
}
private IEnumerator GetStringFromServer(string url, GoogleServerResponse myEvent)
{
Uri www = new Uri(url);
yield return www;
if (myEvent != null)
{
myEvent(www.text);
}
}
}
旁注:避免使用“On”前缀命名事件,调用事件的助手方法应使用[On]EventName
命名约定进行命名。感谢您的回复,但使用操作需要包括哪些内容?我在Unity3D中,它使用Mono(?),我有最小的线索知道什么是兼容的:(我不知道Mono是否实现了操作,如果它不支持操作,你可以传递一个触发事件的委托包装器。愚蠢的问题,我怎么做?
public delegate void GoogleServerResponse(string result);
public class PassEvent
{
public static event GoogleServerResponse OnGoogleServerResponse;
private void Start()
{
print("going to google...");
StartCoroutine(GetStringFromServer("http://google.com", OnGoogleServerResponse));
}
private void print(string p)
{
}
private void StartCoroutine(IEnumerator enumerator)
{
}
private IEnumerator GetStringFromServer(string url, GoogleServerResponse myEvent)
{
Uri www = new Uri(url);
yield return www;
if (myEvent != null)
{
myEvent(www.text);
}
}
}