【问题标题】:Are DLLs loaded by reflection being cached?通过反射加载的 DLL 是否被缓存?
【发布时间】:2015-04-10 13:35:43
【问题描述】:

我有一个应用程序可以根据需要通过反射加载类型,因为配置可能会更改实现。 这是一个示例代码:

var myObject = Activator.CreateInstance(Type.GetType("MyAssembly.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1r46a5dfa04dase2"))as IMyClass

我的问题在这里,这个类型是默认缓存还是每次都会重新加载,如果没有,我该如何缓存它以提高性能?

【问题讨论】:

    标签: c# .net caching dll reflection


    【解决方案1】:

    一旦加载,程序集就无法卸载(除非您卸载加载它的完整 AppDomain)(例如参见 How to unload an assembly from the primary AppDomain?)。所以你的问题正好相反:-)

    现在...你肯定可以加快一切:

    Type myType = Type.GetType("MyAssembly.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1r46a5dfa04dase2");
    

    每次都需要执行此调用。虽然不会加载程序集,但会在程序集中进行搜索。你可以缓存myType

    var myObject = Activator.CreateInstance(myType) as IMyClass;
    

    这将每次搜索myType 的无参数构造函数。您可以通过缓存所需的构造函数 (myConstructor) 来加快速度:

    ConstructorInfo myConstructor = myType.GetConstructor(Type.EmptyTypes);
    
    var myObject = myConstructor.Invoke(null) as IMyClass;
    

    现在...即使使用反射也很慢...您可以创建一个动态方法来调用构造函数并将其缓存:

    Func<IMyClass> myCreate = Expression.Lambda<Func<IMyClass>>(Expression.New(myConstructor)).Compile();
    
    var myObject = myCreate();
    

    所以最后你只能缓存myCreate :-)

    【讨论】:

      【解决方案2】:

      与实例不同,单一类型及其包含的程序集一旦使用就不会被卸载(假设只有一个 AppDomain),所以基本上答案是肯定的,有一个缓存。

      也可以看看这里: Can you remove an Add-ed Type in PowerShell again?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-11
        • 1970-01-01
        • 1970-01-01
        • 2011-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        相关资源
        最近更新 更多