C# 类不能伪装成另一个类,因为无法覆盖 GetType 方法

标签 c#

通过 C# 在 CLR 中有一个声明说 在 C# 中,一个类不能伪装成另一个类,因为 GetType 是虚拟的,因此不能被覆盖

但我认为在 C# 中我们仍然可以隐藏 GetType 的父实现。

我一定是错过了什么

如果我隐藏基本的 GetType 实现,那么我可以将我的类伪装成另一个类,对吗?

这里的关键不在于GetType是否是虚拟的,问题在于我们能否在C#中将一个类伪装成另一个类

以下是可能重复的 NO.4 答案,所以我的问题更多关于这个。 这种伪装是否可能,如果可以,我们怎么能说我们可以防止 C# 中的类类型伪装?不管 GetType 是不是虚拟的

While its true that you cannot override the object.GetType() method, you can use "new" to overload it completely, thereby spoofing another known type. This is interesting, however, I haven't figured out how to create an instance of the "Type" object from scratch, so the example below pretends to be another type.

public class NotAString {
    private string m_RealString = string.Empty;
    public new Type GetType()
    {
        return m_RealString.GetType();
    } } 

After creating an instance of this, (new NotAString()).GetType(), will indeed return the type for a string.

share|edit|flag answered Mar 15 at 18:39

Dr Snooze 213 By almost anything that looks at GetType has an instance of object, or at the very least some base type that they control or can reason about. If you already have an instance of the most derived type then there is no need to call GetType on it. The point is as long as someone uses GetType on an object they can be sure it's the system's implementation, not any other custom definition. – Servy Mar 15 at 18:54 add comment

最佳答案

这个问题只有在你定义上下文时才有意义:
对谁/什么伪装?

有几个选项:

  1. 伪装以便运行时将其解释为不同的类型:
    不可能使用此方法。运行时甚至不调用 GetType

  2. 伪装成其他库将其解释为不同的类型:
    不可能使用此方法。如果库采用 B 你不能传递你的类 X,如果库采用 object 它不会调用你的 GetType,因为它是 new,而不是 override

  3. 伪装以便开发人员在调试时可能认为它是其他类型:
    可能(如果他没有注意到你的把戏)。但是,为什么?

关于C# 类不能伪装成另一个类,因为无法覆盖 GetType 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17311040/

相关文章:

c# - 授权 header 需要 'Credential'参数

C# Regex - 如何从字符串中删除多个成对的括号

c# - VSTS - 在部署之前使应用程序离线

c# - 4.4 Bot Framework 中的 AzureBlobStorage 实现

c# - Ubuntu 上的目标语言是什么?

c# - C++ dll 将数组传递给 C#

c# - 在 C# 中使用 GitLabCI

c# - 将参数作为字典对象传递给 JavaScript 函数

c# - 在 c#.net 中取消选中复选框时如何更改项目的颜色?

c# - NHibernate 投影和 "Having"子句