2011-11-07 68 views
0

[我已經張貼一些非常相似,但這個問題並不好,這裏是我真的想知道]從DLL/Assembly獲取實例?

我得到了下面的代碼生成一個DLL:

public class MyObject : DependencyObject 
{ 
} 


public class Timer : DependencyObject 
{ 
} 

public class AnotherClass 
{ 
} 

public class Test 
{ 
    MyObject q1 = new MyObject(); 
    MyObject q2 = new MyObject(); 
    MyObject q3 = new MyObject(); 
    MyObject q4 = new MyObject(); 

    Timer t1 = new Timer(); 
    Timer t2 = new Timer(); 
    Timer t3 = new Timer(); 

    AnotherClass a1 = new AnotherClass(); 
    AnotherClass a2 = new AnotherClass(); 
    AnotherClass a3 = new AnotherClass(); 
    } 
} 

然後我會喜歡從我的DLL文件中提取實例。下面是我得到的那一刻:

var library = Assembly.LoadFrom(libraryPath); 

但後來,我還沒有有關如何提取我的10個實例(4個MyObjects,3個定時器& 3 AnotherClasses)任何想法。我設法得到的唯一的事情就是4類(爲MyObject,定時器,AnotherClass和測試)的代碼:

IEnumerable<Type> types = library.GetTypes(); 

,但我覺得這不是我會得到我的10個實例的方式......

(PS:我甚至不能確定的10個實例包含在我的DLL文件...)

+2

你不能只是在消費項目中引用你的DLL,然後像使用任何其他類庫一樣使用它嗎? –

+0

Nop,我可以,因爲我會動態加載任何DLL在一個特定的文件夾:/ –

+0

是否有一個具體的原因,你這樣做,而不是包括DLL爲您的項目的一部分? –

回答

2

您無法輕鬆獲取給定類型的所有實例。這根本不存在,除了一些漂亮的硬核調試API(想想:SOS)。如果你需要這個,你應該考慮一些其他的,可管理的跟蹤你的實例的方法(最好不要讓它們保持活着,所以WeakReference)。

+0

+1有一些好的框架在那裏管理外部對象,即MEF> http://mef.codeplex.com/ – MattDavey

1

您需要實例的Test一個實例。這些實例在你做之前不會存在。

現在,我懷疑你真的想要做的是有一個單身人士(由於多種原因皺眉設計模式)。然而,這是你會怎麼做,如果你想它:

public class Test 
{ 
    private static Test instance_ = new Test(); 

    MyObject q1 = new MyObject(); 
    MyObject q2 = new MyObject(); 
    MyObject q3 = new MyObject(); 
    MyObject q4 = new MyObject(); 

    Timer t1 = new Timer(); 
    Timer t2 = new Timer(); 
    Timer t3 = new Timer(); 

    AnotherClass a1 = new AnotherClass(); 
    AnotherClass a2 = new AnotherClass(); 
    AnotherClass a3 = new AnotherClass(); 

    public Test Instance { get { return instance_; } } 
} 

現在,假設你讓這些成員公開可用的,你可以在他們得到:

Test.Instance.a1; // etc... 

現在,我已經說過,單身人士通常不是一個好主意。最好從你的依賴模塊中實例化你自己的Test實例並使用它。