首页 > 解决方案 > 有没有办法使用参数来设置变量名?

问题描述

我真的不知道如何解释这一点,但是有没有办法使用字符串来放置变量的名称?我有一些代码来解释我的问题:

我的用户类有用户名、ID 和许多其他内容。

public User User;

我有下载包含所有信息的json的功能

public IEnumerator getDataArray(string function, string value, targetObject)
{
    queuedDownloads++;

    Dictionary<string, string> headerDict = new Dictionary<string, string>();
    headerDict.Add(function, value);
#if UNITY_EDITOR
        headerDict.Add("UserID", userID.ToString());
#endif
        UnityWebRequest www = UnityWebRequest.Post(downloadUrl, headerDict);
    yield return www.SendWebRequest();

    if (www.isNetworkError || www.isHttpError)
    {
        Debug.Log("<color=red>" + www.error + "</color>");
        string errorMessage = www.error;
        Debug.Log("There was an error getting the data list: " + errorMessage);
    }
    else
    {
        string result = HTMLEntityUtility.Decode(www.downloadHandler.text);
        if (result.Length == 0)
        {
            Debug.Log("EMPTY");
        }
        else
        {
            //here i want that targetObject becomes the name of the given value
            //the wanted line here is:
            //User = JsonExtension.GetArrayFromJson<User>(result);
            targetObject = JsonExtension.GetArrayFromJson<targetObject>(result);
            queuedDownloads--;
        }
    }

    yield return null;
}

我想使用此功能通过 webrequest 获取信息并将该数据保存在用户类中。要开始这个我想使用这样的东西:

    //here I want to give which data it has to request, what value has to be used and in which variable this has to be stored
    StartCoroutine(getDataArray("getUserData", "1", User));

我有多个类,我想像这样填充,但我不想要 14 个不同的函数,除了 1 个变量之外是相同的。有没有办法让上述函数中的 targetObject 作为我在协程中给出的变量的名称?

标签: c#unity3d

解决方案


当然,这取决于它的JsonExtension.GetArrayFromJson工作方式,但我认为您可以使您的例程通用

// The type parameter T is hereby extracted automatically from the reference
// you pass into "targetObject"
public IEnumerator getDataArray<T>(string function, string value, ref T targetObject)
{
    queuedDownloads++;

    var headerDict = new Dictionary<string, string>();
    headerDict.Add(function, value);

#if UNITY_EDITOR
    headerDict.Add("UserID", userID.ToString());
#endif

    using(var www = UnityWebRequest.Post(downloadUrl, headerDict))
    {
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.LogError($"There was an error getting the data list: <color=red>{www.error}</color>");
            return;
        }

        var result = HTMLEntityUtility.Decode(www.downloadHandler.text);
        if (string.IsNullOrWhiteSpace(result))
        {
            Debug.LogError("The result is EMPTY!");
            return;
        }

        // Here you use the generic type parameter "T"
        targetObject = JsonExtension.GetArrayFromJson<T>(result);
    }

    queuedDownloads--;
}

你会这样称呼它,例如

User user;
SomeOtherClass someOtherClass;

StartCoroutine(getDataArray("getUserData", "1", user));
StartCoroutine(getDataArray("getSomeOtherData", "XY", someOtherClass));

正如所说的传入类型参数,T例如

StartCoroutine(getDataArray<User>("getUserData", "1", user));

没有必要/将是多余的,因为它是从您传入的对象的类型中自动提取的targetObject


一般来说:

请注意,现在您将能够使用正确的引用等启动协程,但是......您永远不会知道是否何时会收到实际结果。

您可能更应该实现一个回调,它一旦实际存在就处理数据,例如

public IEnumerator getDataArray<T>(string function, string value, Action<T> onSuccess)
{
    [.....]

    // Here you use the generic type parameter "T"
    T targetObject = JsonExtension.GetArrayFromJson<T>(result);

    queuedDownloads--;
    
    // Invoke the callback
    onSuccess?.Invoke(targetObject);
}

并称它为例如

StartCoroutine(getDataArray("getUserData", "1", HandleReceivedUser));

...

private void HandleReceivedUser(User user)
{
    // do something with the user
}

推荐阅读