Open jborean93 opened 8 months ago
Just for future reference here is how you can define a class that implements such an interface with TypeBuilder
using namespace System.Reflection
using namespace System.Reflection.Emit
$ErrorActionPreference = 'Stop'
Add-Type -TypeDefinition @'
public interface IMethod
{
static abstract int GetId();
}
'@
$ab = [AssemblyBuilder]::DefineDynamicAssembly(
[AssemblyName]::new("MyAssembly"),
[AssemblyBuilderAccess]::Run)
$mb = $ab.DefineDynamicModule("MyModule")
$tb = $mb.DefineType(
"MyClass",
[TypeAttributes]::Public,
$null,
[type[]]@([IMethod]))
$getAttr = $tb.DefineMethod(
"GetId",
[MethodAttributes]"Public, Static",
[int],
[type]::EmptyTypes)
$getAttrIl = $getAttr.GetILGenerator()
$getAttrIl.Emit([OpCodes]::Ldc_I4_1)
$getAttrIL.Emit([OpCodes]::Ret)
$tb.DefineMethodOverride($getAttr, [IMethod].GetMethod("GetId"))
$null = $tb.CreateType()
[MyClass]::GetId()
How can you have static properties or methods on an interface when an interface depends on having a 'this'?
I would have expected the only static things an interface could have would be constants.
How do you invoke a static method on an interface?
It's a new feature added in C# 11 https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members. Just like any other static property/method, the implementation can only reference other static properties/methods on that same interface/type.
How do you invoke a static method on an interface?
You don't invoke it on the interface you still invoke it on the class that implements the abstract property/method.
Add-Type @'
public interface IMethod
{
static abstract int GetId();
}
public class MyClass : IMethod
{
public static int GetId() => 1;
}
public class OtherClass
{
// Demonstrates how it can be used in C#
public static int Test<T>() where T : IMethod => T.GetId();
}
'@
# Can be called directly on the class like any other static member
[MyClass]::GetId()
[OtherClass]::Test[MyClass]()
This advanced tutorial demonstrates scenarios for operators and other static members in interfaces.
The Engine WG reviewed this issue and happy to see this enhancement to PowerShell class.
Prerequisites
Steps to reproduce
Expected behavior
Actual behavior
Error details
Environment data
Visuals
No response