c# - "final"在 IL 中是什么意思?

标签 c# overriding clr cil

使用 ildasm/ilasm 时,您可以观察编译器(例如 C# 编译器)生成的 MSIL/CIL 代码,在某些情况下,您可以看到标记为 virtual final 的方法。

在这种情况下,final 是什么意思?我的猜测是它的意思是“这个方法不能被覆盖”,所以即使这个方法在虚拟表中有一个槽,那个槽也不能被派生类中的方法覆盖。

但是怎么办?它在实践中如何运作?

它是由编译器强制执行的(例如,如果您尝试覆盖密封方法,它将因编译错误而失败)还是由 CLR 强制执行(例如,当您尝试覆盖方法时,CLR 会抛出异常),还是由两者强制执行? 是否有任何合法的方式“删除”、规避此 final ,即编写覆盖此方法的派生类?

更新:我可能找到了一种方法(参见我自己的回答),但我完全不确定这是合法的、受支持的、标准的……所以我在这个新问题上发布了另一个问题(但相关)问题 here

我愿意接受评论,当然还有其他方法(如果存在的话!)。

最佳答案

这是针对来自某个接口(interface)的方法。它是一个实现细节。如果一个类实现了一些接口(interface),那么接口(interface)中的方法被标记为virtual,即用于多态行为(虚拟表(v表)中的一个地方)。但它也被标记为 final (Sealed) 以便实现基类的其他子类无法覆盖该特定方法。

考虑以下示例:

interface SomeInterface
{
    void SomeMethod();
}

class SomeClass : SomeInterface
{
    public void SomeMethod() //This will be marked as virtual final in IL
    {
        //anything
    }
}

发件人:CLR via C# (Jeffrey Richter)

The C# compiler requires that a method that implements an interface method signature be marked as public. The CLR requires that interface method be marked as virtual. If you do not explicitly mark the method as virtual in your source code, the compiler marks the method as virtual and sealed; this prevents a derived class from overriding the interface method. If you explicitly mark the method as virtual, the compiler marks the method as virtual (and leaves it unsealed); this allows a derived class to override the interface method.

关于c# - "final"在 IL 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33944089/

相关文章:

c# - Linq:当我在 XML 文件中有命名空间时,元素不起作用

c# - 不在 View 中显示属性

java - 您能否分析一下有关继承的 JAVA 代码的输出

c# - myval = (someconditon) 吗?一些值 : myval get optimized to not set the value in case it's false

c# - 如何在 30 秒后删除文件/或在作业完成后删除一次文件

c# - 结束对话 C# 机器人

c# - 作为静态或非静态类的存储库?

c# - 在 SQL Server 中创建自定义程序集抛出在数据库错误中找不到程序集

css - CSS "!important"标签是否跨浏览器?

java - 我们为什么要覆盖一个方法?