Method Overloading
Проверено с версией:: 4.1
-
Сложность: Средняя
How to overload methods to create different methods with the same name.


Method Overloading
Средняя Scripting
SomeClass
Code snippet
using UnityEngine;
using System.Collections;
public class SomeClass
{
//The first Add method has a signature of
//"Add(int, int)". This signature must be unique.
public int Add(int num1, int num2)
{
return num1 + num2;
}
//The second Add method has a sugnature of
//"Add(string, string)". Again, this must be unique.
public string Add(string str1, string str2)
{
return str1 + str2;
}
}
#pragma strict
public class SomeClass
{
//The first Add method has a signature of
//"Add(int, int)". This signature must be unique.
function Add(num1 : int, num2 : int) : int
{
return num1 + num2;
}
//The second Add method has a sugnature of
//"Add(string, string)". Again, this must be unique.
function Add(str1 : String, str2 : String) : String
{
return str1 + str2;
}
}
import UnityEngine
import System.Collections
public class SomeClass:
//The first Add method has a signature of
//"Add(int, int)". This signature must be unique.
public def Add(num1 as int, num2 as int) as int:
return (num1 + num2)
//The second Add method has a sugnature of
//"Add(string, string)". Again, this must be unique.
public def Add(str1 as string, str2 as string) as string:
return (str1 + str2)
SomeOtherClass
Code snippet
using UnityEngine;
using System.Collections;
public class SomeOtherClass : MonoBehaviour
{
void Start ()
{
SomeClass myClass = new SomeClass();
//The specific Add method called will depend on
//the arguments passed in.
myClass.Add (1, 2);
myClass.Add ("Hello ", "World");
}
}
#pragma strict
function Start ()
{
var myClass = new SomeClass();
//The specific Add method called will depend on
//the arguments passed in.
myClass.Add (1, 2);
myClass.Add ("Hello ", "World");
}
import UnityEngine
import System.Collections
public class SomeOtherClass(MonoBehaviour):
private def Start():
myClass = SomeClass()
//The specific Add method called will depend on
//the arguments passed in.
myClass.Add(1, 2)
myClass.Add('Hello ', 'World')
Связанные обучающие материалы
- Variables and Functions (Урок)