說我有下面的類結構:C#泛型:修改隱藏繼承成員在派生類中
public class A {
public string Name { get; set; }
}
public class B : A {
public new string Name {
get { return base.Name; }
set { base.Name = value + " set in B"; }
}
}
public static class Test {
public static void SetAndPrintName<T>(T value, string name) where T : A {
value.Name = name;
Console.WriteLine(value.Name);
}
}
這裏的結果,我期望從運行下面的代碼:
Test.SetAndPrintName(new A(), "a");
Test.SetAndPrintName(new B(), "b");
----
a
b set in B
相反,我得到:
a
b
由於沒有工作,我試着在鑄造,這是醜陋的,但和預期一樣:
public static void SetAndPrintName<T>(T value, string name) where T : A {
if (value is B) {
((B)(object)value).Name = name;
} else {
value.Name = name;
}
Console.WriteLine(value.Name);
}
----
Test.SetAndPrintName(new A(), "a");
Test.SetAndPrintName(new B(), "b");
----
a
b set in B
我也試圖使Name
財產虛擬/重寫和工作太:
public class A {
public virtual string Name { get; set; }
}
public class B : A {
public override string Name {
get { return base.Name; }
set { base.Name = value + " set in B"; }
}
}
----
Test.SetAndPrintName(new A(), "a");
Test.SetAndPrintName(new B(), "b");
----
a
b set in B
的問題是:爲什麼不new
工作像其他?通用方法知道value
的類型爲B
,那麼爲什麼C#將它視爲一個A
三分之一?
'new'關鍵字本質上並不意味着'virtual'。通用實現不會改變這一點。 – haim770