[.NET]Overload Method

觀看「.NET Puzzles, Gotchas & Cautionary Tales」這課程,把Overload的相關內容整理下來跟大家分享!

以下建立3個不同參數型態的Overload Method,如下,

private string OverloadTest(Int32 value)
{
	return "Int32";
}

private string OverloadTest(Int64 value)
{
	return "Int64";
}

private string OverloadTest(object value)
{
	return "Object";
}

 

然後程式設定不同的型態變數去呼叫它,如下,

Int32 i32 = 123;
Int64 i64 = 123;
Int16 i16 = 123;
string sObj = "123";

Console.WriteLine("OverloadTest(i32):{0}", OverloadTest(i32));
Console.WriteLine("OverloadTest(i64):{0}", OverloadTest(i64));
Console.WriteLine("OverloadTest(sObj):{0}", OverloadTest(sObj));
Console.WriteLine("OverloadTest(i16):{0}", OverloadTest(i16));

image

 

因為i16變數的型態為Int16並沒有辦法直接Match到OverloadTest的參數內容。

所以就會被以最接近的資料型態去對應它,所以Int16最接近的資料型態就是Int32。

如果您使用VS2013的話,馬上就會看到OverloadTest(Int32 value)上面的顯示 2 references,如下,

image

 

所以,如果把OverloadTest(Int64 value) Method給刪掉,那OverloadTest(i64)就會Call OverloadTest(object value)這個Method,如下,

image

 

再來,如下我們新增一個泛型的Method,那結果會變成怎樣呢?

private string OverloadTest<T>(T value)
{
	return "Generic";
}

 

可以發現,string, Int16, Int64的變數,因為沒有辦法直接Match到OverloadTest的參數內容,所以就會使用泛型的Overload Method,如下,

image

image

 

那如果再把物件的繼承加進來,又會變成如何呢?

1.

class C1
{
	public string test(string s)
	{
		return "string";
	}

	public string test(object x)
	{
		return "object";
	}
}

class C11 : C1
{
}

 

如果建立C11然後Call test(""),相當然會Call到C1的test(string s) Method,如下,

var myC11 = new C11();
Console.WriteLine(myC11.test(""));

image

 

2.

class C2
{
	public string test(string s)
	{
		return "string";
	}
}

class C22: C2
{
	public string test(object s)
	{
		return "object";
	}
}

 

一樣,我們建立C22然後Call test(""),那會呼叫 C22 的 test(object s) Method 還是 C2 的 test(string s) Method呢?

var myC22 = new C22();
Console.WriteLine(myC22.test(""));

image

 

3.

class C3
{
	public string test(string s)
	{
		return "string";
	}

	public virtual string test(object s)
	{
		return "base object";
	}
}

class C33 : C3
{
	public override string test(object s)
	{
		return "override object";
	}
}

 

一樣,我們建立C33然後Call test(""),那會呼叫 C33 的 override string test(object s) Method 還是 C3 的 test(object s) Method呢?

var myC33 = new C33();
Console.WriteLine(myC33.test("")); 

image

 

它是呼叫C3的test(object s) Method哦! 它遇到了 override 就會忽略它,因為C33沒有其他的Method,所以就後C1去找Match的Method,就找到了 C3 的 test(object s) Method!

是不是很有趣呢!

 

參考資料

.NET Puzzles, Gotchas & Cautionary Tales

Kathleen Dollard's view of life and .NET development

7.4.2 多載解析

 

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^