假设我有以下 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/