SoFunction
Updated on 2025-05-16

Detailed explanation of C#'s example of implementing interfaces through scripts

In the past, the delegate injection mode used by C# scripts, today, at the prompt, try to directly implement the interface with the script, and then C# can dynamically or specify a new type to create an interface implementation object. From a code perspective, it is a bit complicated, but the scripting aspect seems more concise and organized.

Reference packages are required, etc., and other are automatically added:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="" version="2.14.1" targetFramework="net472" />
  <package id="" version="8.0.0" targetFramework="net472" />
  <package id="" version="4.13.0" targetFramework="net472" />
  <package id="" version="3.11.0" targetFramework="net472" developmentDependency="true" />
  <package id="" version="4.13.0" targetFramework="net472" />
  <package id="" version="4.13.0" targetFramework="net472" />
  <package id="" version="4.13.0" targetFramework="net472" />
  <package id="" version="4.13.0" targetFramework="net472" />
  <package id="" version="4.13.0" targetFramework="net472" />
  <package id="" version="4.13.0" targetFramework="net472" />
  <package id="" version="4.13.0" targetFramework="net472" />
  <package id="" version="4.13.0" targetFramework="net472" />
  <package id="" version="4.7.0" targetFramework="net472" />
  <package id="" version="4.5.1" targetFramework="net472" />
  <package id="" version="8.0.0" targetFramework="net472" />
  <package id="" version="8.0.0" targetFramework="net472" />
  <package id="" version="8.0.0" targetFramework="net472" />
  <package id="" version="8.0.0" targetFramework="net472" />
  <package id="" version="8.0.0" targetFramework="net472" />
  <package id="" version="8.0.0" targetFramework="net472" />
  <package id="" version="8.0.0" targetFramework="net472" />
  <package id="" version="8.0.0" targetFramework="net472" />
  <package id="" version="4.5.5" targetFramework="net472" />
  <package id="" version="4.5.0" targetFramework="net472" />
  <package id="" version="8.0.0" targetFramework="net472" />
  <package id="" version="6.0.0" targetFramework="net472" />
  <package id="" version="7.0.0" targetFramework="net472" />
  <package id="" version="7.0.0" targetFramework="net472" />
  <package id="" version="4.5.4" targetFramework="net472" />
</packages>

The interface is defined as follows:

namespace WindowsFormsApp1
{
    public interface IFlexiblePluginAgent
    {
        string RegistDrType();
    }
}

The verification file is as follows:

using System;
using ;
 
public class FlexiblePluginAgentProcessScriptXXXX : 
{
	public string RegistDrType()
	{
		return "scritp_drv";
	}
}

The loading and verification code is as follows:

using ;
using ;
using ;
using System;
using ;
using ;
using ;
using ;
 
namespace WindowsFormsApp1
{
    internal static class Program
    {
        /// &lt;summary&gt;
        /// The main entry point of the application.        /// &lt;/summary&gt;
        [STAThread]
        static void Main()
        {
            ScriptTest();
        }
        static void ScriptTest()
        {
            try
            {
                // Read external code files                string codeFilePath = "";
                string sourceCode = (codeFilePath);
 
                var compilation = ("DynamicAssembly")
                    .WithOptions(new CSharpCompilationOptions())
                    .AddReferences((typeof(object).))
                    .AddReferences((typeof(IFlexiblePluginAgent).))
                    .AddSyntaxTrees((sourceCode));
 
                // Check for compilation errors                var diagnostics = ();
                if (())
                {
                    ("Compilation error:");
                    foreach (var diagnostic in (d =&gt;  == ))
                    {
                        (());
                    }
                    return;
                }
 
                // Generate assembly in memory                using (var ms = new MemoryStream())
                {
                    EmitResult emitResult = (ms);
 
                    if (!)
                    {
                        ("Assembly generation failed:");
                        foreach (var diagnostic in (d =&gt;  == ))
                        {
                            (());
                        }
                        return;
                    }
 
                    (0, );
                    Assembly assembly = (());
 
                    ("---Check whether there are IFlexiblePluginAgent derived classes in the assembly---");
                    var derivedTypes = 
                        .Where(t =&gt; typeof(IFlexiblePluginAgent).IsAssignableFrom(t) &amp;&amp; !)
                        .ToList();
 
                    if (())
                    {
                        ("Finding the following IFlexiblePluginAgent derived class:");
                        foreach (var type in derivedTypes)
                        {
                            ($"  - {}");
                        }
 
                        // Create an object using the first derived class                        Type agentType = ().AsType();
                        IFlexiblePluginAgent agent = (IFlexiblePluginAgent)(agentType);
                        string result = ();
 
                        ($"Registered DrType yes: {result}");
                    }
                    else
                    {
                        ("The derived class of IFlexiblePluginAgent was not found");
                    }
 
                    ("------------------------------------------------------------------------------------------------------------------------------);
                    Type agentType2 = ("FlexiblePluginAgentProcessScriptXXXX");
                    if (agentType2 == null)
                    {
                        ("MyPluginAgent type not found");
                        return;
                    }
 
                    IFlexiblePluginAgent agent2 = (IFlexiblePluginAgent)(agentType2);
                    string result2 = ();
 
                    ($"Registered DrType yes: {result2}");
 
                }
            }
            catch (Exception ex)
            {
                ($"An error occurred: {}");
            }
        }
    }
    // Extended method is used to check diagnostic information    public static class DiagnosticExtensions
    {
        public static bool HasAnyErrors(this IEnumerable&lt;Diagnostic&gt; diagnostics)
        {
            return (d =&gt;  == );
        }
    }
}

This is the end of this article about the detailed explanation of C#’s interface through scripts. For more related C# interface content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!