这个过程并没有那么复杂,假设您的回调总是这样
void(SomeStateclass)
.
更换
JSonState
在上面的代码中使用泛型T可以实现这一目的。这就是你最终的结果:
// The DataController takes a generic T respresenting one of your State classes
// notice that we need a constraint for the type T to have a parameterless constructor
public class DataController<T> : MonoBehaviour where T: new()
{
// the delegate takes the generic type, so we only need one
public delegate void CallbackAjaxFinished(T j);
public CallbackAjaxFinished cbAjaxFinished = null;
public void AjaxStateGet(CallbackAjaxFinished cb=null)
{
/* make the Ajax call*/
cbAjaxFinished = cb;
new HTTPRequest(
new Uri(baseURL + _urlGetState),
HTTPMethods.Get, AjaxStateGetFinished
).Send();
}
private void AjaxStateGetFinished(
HTTPRequest request, HTTPResponse response
) {
if (response == null) {
return;
}
// here we use the default keyword to get
// an instance of an initialized stronglytyped T
T j = default(T);
try {
// the T goes into the FromJson call as that one was already generic
j = JsonUtility.FromJson<T>(response.DataAsText);
if (cbAjaxFinished != null) {
cbAjaxFinished(j);
}
} catch (ArgumentException) { /* Conversion problem */
TryDisplayFatalError(FatalErrors[FatalError.ConversionProblem2]);
}
}
}
仅此而已。您的datacontroller类现在是泛型的。
您可以这样使用它:
var dc = new DataController<JsonState>()
dc.AjaxStateGet( (v) => {
v.Dump("jsonstate");
});
var dc2 = new DataController<JsonState2>();
dc2.AjaxStateGet( (v) => {
v.Dump("jsonstate2");
});