Unity3d UnityScript中的函数向下转换

Unity3d UnityScript中的函数向下转换,unity3d,unityscript,Unity3d,Unityscript,实际上,我在Unity论坛上发布了这篇文章,但我的语言相关问题似乎都没有在那里得到回答。假设我在Unity脚本中定义了一个函数: function GetSomething : SomeClass { return new SomeClass(); } 其中SomeClass是在别处定义的某个类。现在,我有一个变量,Function,类型为Function,我想确保它返回一些东西,任何东西。因此,我要做的是: // theFunction is set to GetSomething s

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

function GetSomething : SomeClass
{
   return new SomeClass();
}
其中SomeClass是在别处定义的某个类。现在,我有一个变量,Function,类型为Function,我想确保它返回一些东西,任何东西。因此,我要做的是:

// 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.
不幸的是,在上面的代码中,returnsMething函数将为null。为了使其不为null,我必须更加具体并强制转换为function():SomeClass,或者只重写函数定义以返回一个对象,如下所示:

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

这是非常恼人的,因为它很容易忘记执行:Object(特别是如果您忽略它,它将正确地推断它是返回类型SomeClass),并且结果不是错误,而是一个非常微妙的错误,因为强制转换失败。是否有任何方法可以获得我想要的行为,即正确向下转换为function():Object,就像我可以向下转换普通对象一样?

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

#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>();
}
#pragma strict
导入System.Collections.Generic;
函数启动()
{
//该函数设置为在程序中的其他地方获取某些内容。
var functionthattreturnssomething=GetSomething as function():对象;
if(返回方法的函数!=null)
{
//…调用它并使用返回的值执行操作。
Log(返回方法的函数);
}
else Debug.Log(“null”);
}
函数GetSomething():List。
{
返回新列表。();
}

erm。。为什么不直接按名字调用函数呢?拥有一个自己的对象有什么意义?我的程序并没有真正做到上面所说的,这是一种从一个可以容纳回调的类中出现的情况。回调函数的类型是Function,API的用户可以选择提供一个回调函数,该回调函数要么返回一个值(并且该值被使用),要么返回void。我使用类型转换来检查我所处的情况。所以我同意,为什么要制作对象?为什么不设置并获取这一条数据呢?