gpt4 book ai didi

c# - 为什么 Object.GetType() 不是虚拟的?

转载 作者:可可西里 更新时间:2023-11-01 02:59:52 24 4
gpt4 key购买 nike

取自 MSDN 的代码示例

public class Test {
public static void Main() {
MyBaseClass myBase = new MyBaseClass();
MyDerivedClass myDerived = new MyDerivedClass();
object o = myDerived;
MyBaseClass b = myDerived;

Console.WriteLine("mybase: Type is {0}", myBase.GetType());
Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType()); }}

/*
This code produces the following output.
mybase: Type is MyBaseClass
myDerived: Type is MyDerivedClass
object o = myDerived: Type is MyDerivedClass
MyBaseClass b = myDerived: Type is MyDerivedClass
*/

那么将 GetType() 设为虚拟是否合乎逻辑,至少它可以像虚拟一样工作?任何人都可以解释一下吗?以及其他问题 NET 框架中是否有任何其他方法具有类似于 GetType 的行为?

最佳答案

因为 .Net 框架不希望您覆盖 GetType() 方法和关于类型的欺骗

假设您可以覆盖该方法,除了返回实例的类型之外,您还希望它做什么。当您覆盖每个类的方法以返回实例的类型时,您是否违反了 DRY。

关于c# - 为什么 Object.GetType() 不是虚拟的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3253329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com