-new-關鍵詞在這裏是什麼意思?關鍵字-new-之前的方法實現
class X
{
new byte Method()
{
return 5;
}
}
我在stackoverflow上找到了一些,但我需要最簡單的答案(可憐的英語)。
-new-關鍵詞在這裏是什麼意思?關鍵字-new-之前的方法實現
class X
{
new byte Method()
{
return 5;
}
}
我在stackoverflow上找到了一些,但我需要最簡單的答案(可憐的英語)。
new
隱藏從基類中的方法:
class Base
{
byte Method()
{
return 4;
}
}
class X : Base
{
new byte Method()
{
return 5;
}
}
X x = new X();
Base b = x;
Console.WriteLine(x.Method()); // Prints "5"
Console.WriteLine(b.Method()); // Prints "4"
值得注意的是,如果該方法是虛擬的,並使用override
代替new
,行爲是不同的:
class Base
{
virtual byte Method()
{
return 4;
}
}
class X : Base
{
override byte Method()
{
return 5;
}
}
X x = new X();
Base b = x;
Console.WriteLine(x.Method()); // Prints "5"
Console.WriteLine(b.Method()); // Prints "5"
其new關鍵字。如果在方法上使用,則隱藏現有的繼承方法。
在你的情況下,因爲X
不是從任何類派生,你會得到一個警告說new
關鍵字不會隱藏任何現有的方法。
此外,該方法是私人的(默認情況下),不能在課堂以外訪問。
如果X
從具有該方法的類派生,它將隱藏它。 @phoog在他的回答中有很好的例子。
在上面的代碼情況下,它不會使實際使用new關鍵字多大意義。因爲它不會繼承除System.Object之外的任何其他類(默認情況下)。 – Zenwalker 2012-03-01 07:54:05