c# - 在 C# 中使用静态方法实现接口(interface)

标签 c# .net clr il

假设我有以下 ILAsm 代码:​​

    .class public interface abstract ITest
    {
        .field public static int32 counter

        .method public static void StaticMethod(string str)
        {
            ldarg.0
            call void [mscorlib]System.Console::WriteLine(string)
            ret
        }

        .method public virtual abstract void InstMethod(string) { }
    }

是否可以在 C# 中定义一个实现此 ITest 接口(interface)的类?

我可以在 ILAsm 中实现这个接口(interface):

    .class public TestImpl extends [mscorlib]System.Object implements ITest
    {
        .method public virtual void InstMethod(string str)
        {
            ldarg.1
            call void ITest::StaticMethod(string)
            ret
        }

        .method public specialname rtspecialname instance void .ctor()
        {
            ldarg.0
            call instance void .base::.ctor()
            ret
        }
    }

并在 C# 代码中成功使用已实现的类:

        var testImpl = new TestImpl();
        testImpl.InstMethod("I'm static!"); 

但是如何在 C# 中实现这个接口(interface)呢?

最佳答案

令人惊讶的是(至少对我而言),您的 IL 代码编译和验证(为此使用 PEVerify)很好(假设您添加了一些 .assembly 指令)。

这是由 CLI 规范(§I.8.9.4 接口(interface)类型定义)支持的:

[…] an interface type definition shall not provide field definitions for values of the interface type (i.e., instance fields), although it can declare static fields.

[…] An interface type definition can define and implement static methods since static methods are associated with the interface type itself rather than with any value of the type.

但这样做不符合 CLS:

CLS Rule 19: CLS-compliant interfaces shall not define static methods, nor shall they define fields.

并且您可以在 C# 中实现该接口(interface)。以下代码可以编译并正常工作:

class Test : ITest
{
    public void InstMethod(string s)
    { }
}

但看起来您无法从 C# 访问静态字段或静态方法。

关于c# - 在 C# 中使用静态方法实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19496397/

相关文章:

c# - 无法加载 DLL 'db2app64.dll'

c# - 将空的 DateTime 值发送到 SQL 存储过程。但不为空

c# - 当我在两者之间使用 MessageBox.Show() 时,我的代码如何工作,没有它就不能工作?

c# - 为什么 decimal 不是原始类型?

mysql - 尝试连接 asp.net 和 mysql 尝试找出 mysql.data.dll

c# - .NET dll 热插拔,无需重启应用程序

C# 多线程按值传递还是引用传递?

c# - 在我的 CLR 项目中添加包含使得 WLR 无法在启用/clr 的情况下进行编译

c# - 如何在 CLR/托管 C++ 中实现变体类型?

c# - 从字节数组加载时找不到 AppDomain 程序集