代码之家  ›  专栏  ›  技术社区  ›  MarkP

C#ICO反编译器-运行类

c#
  •  4
  • MarkP  · 技术社区  · 14 年前

    我刚刚发现了.NETICodecompiler(请注意,我对它一无所知,只知道它可以在程序中运行程序)。我该如何围绕这一点编写脚本体系结构呢?

    理想情况下,我希望用户编写一些从接口派生的代码。此接口将由我在程序中定义(用户无法编辑)。用户将实现它,编译器引擎将运行它。然后,我的程序将调用它们实现的各种方法。这可行吗?

    public interface IFoo
    {
      void DoSomething();
    }
    

    // Inside my binary
    IFoo pFooImpl = CUserFoo;
    pFooImpl.DoSomething();
    
    2 回复  |  直到 14 年前
        1
  •  2
  •   Aliostad    14 年前

    你想实现的是可能的,但是 当心!! 每次编译代码时,都会将其编译为程序集并加载到内存中。如果更改“脚本”代码并重新编译,它将作为另一个程序集再次加载。这可能会导致“内存泄漏”(尽管它不是真正的泄漏),并且无法卸载那些未使用的程序集。

    唯一的解决办法是 并将该程序集加载到该AppDomain中,然后在代码更改时卸载并再次执行。但要做到这一点要困难得多。

    http://support.microsoft.com/kb/304655

    然后必须使用 程序集.LoadFrom .

        // assuming the assembly has only ONE class
        // implementing the interface and method is void 
        private static void CallDoSomething(string assemblyPath, Type interfaceType, 
            string methodName, object[] parameters)
        {
            Assembly assembly = Assembly.LoadFrom(assemblyPath);
            Type t = assembly.GetTypes().Where(x=>x.GetInterfaces().Count(y=>y==interfaceType)>0).FirstOrDefault();
            if (t == null)
            {
                throw new ApplicationException("No type implements this interface");
            }
            MethodInfo mi = t.GetMethods().Where(x => x.Name == methodName).FirstOrDefault();
            if (mi == null)
            {
                throw new ApplicationException("No such method");
            }
            mi.Invoke(Activator.CreateInstance(t), parameters);
        }
    
        2
  •  1
  •   pierroz    14 年前

    this article 我可以帮你。这是你要找的吗?