【问题标题】:Function Downcasting in UnityScriptUnityScript 中的函数向下转换
【发布时间】:2014-11-11 22:37:33
【问题描述】:

我实际上在 Unity 论坛上发布了这个,但我的语言相关问题似乎都没有在那里得到解答。所以,假设我在 Unity 脚本中定义了一个函数:

function GetSomething : SomeClass
{
   return new SomeClass();
}

SomeClass 是在别处定义的某个类。现在,我有一个函数类型的变量 theFunction,我想确保它返回一些东西,任何东西。所以我要做的是:

// theFunction is set to GetSomething somewhere else in the program.
var functionThatReturnsSomething = theFunction as function() : Object;

if (functionThatReturnsSomething != null)
//... call it and do stuff with the returned value.

现在不幸的是,在上面的代码中,functionThatReturnsSomething 将为空。为了不为空,我必须更具体并强制转换为 function() : SomeClass 或者只是覆盖函数定义以返回一个 Object :

function GetSomething : Object
{
   return new SomeClass();
}

这很烦人,因为它很容易忘记做 :Object (尤其是如果你把它省略了,它会正确地推断它是返回类型 SomeClass),结果不是错误,而是一个非常微妙的错误,因为演员失败。有什么方法可以得到我想要的行为,即正确地向下转换为 function() : Object,就像我可以向下转换普通对象一样?

【问题讨论】:

  • erm.. 你为什么不直接按名称调用函数呢?拥有自己的对象有什么意义?
  • 我的程序实际上并没有执行上述操作,这是由可以保存回调的类引起的。回调是函数类型,API 的用户可以选择提供一个回调,该回调要么返回一个值(并且该值被使用),要么返回一个 void。我使用类型转换来检查我所处的情况。
  • 我同意,为什么要制作这个对象?为什么不直接设置并获取那一条数据呢?

标签: unity3d unityscript


【解决方案1】:

我唯一能想到的是你在声明函数名时忘记了函数名后面的括号。如果我将所有内容放入以下脚本中,将其附加到一个对象并运行它,那么我就可以毫无问题地访问该函数。

#pragma strict

import System.Collections.Generic;

function Start ()
{
    // theFunction is set to GetSomething somewhere else in the program.
    var functionThatReturnsSomething = GetSomething as function() : Object;

    if (functionThatReturnsSomething != null)
    {
        //... call it and do stuff with the returned value.
        Debug.Log(functionThatReturnsSomething);
    }
    else Debug.Log("null");
}

function GetSomething() : List.<int>
{
    return new List.<int>();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多