簡體   English   中英

Activator.CreateInstance需要另一個對象進行實例化

[英]Activator.CreateInstance needs another object to be instantiated

我用經典實例化我的對象

object myObject = Activator.CreateInstance(myType);

代碼,如果工作正常。 問題是,現在,我喜歡實例化一個對象,並且在它的構造函數中,有一個對另一個對象的引用。 所以,如果我只是執行上面的代碼,我得到一個NullReferenceException異常:

Object reference not set to an instance of an object.

我嘗試實例化相關對象(使用Activator.CreateInstance)但我得到了相同的異常...我覺得在我的第二個CreateInstance調用不夠之前實例化有問題的對象。 我該怎么辦 ?

編輯:這是問題的代碼

//A regionManager in needed by MainView as far as I understand the Exception's details
var regionManager = Assembly.LoadFrom("RegionView.dll");
Type rmType = regionManager.GetType("Framework.Hmi.RegionManager");
object obj = Activator.CreateInstance(rmType);
//This works !

var shellViewLibrary = Assembly.LoadFrom("ShellView.dll");
Type svType = shellViewLibrary.GetType("Framework.ShellView.MainView");
object objjj = Activator.CreateInstance(svType);

最后一行失敗,錯誤是NullReferenceException其中包含詳細信息:

at Hmi.RegionManager.get_RegionFactory()
at Hmi.RegionManager.CreateRegion(DependencyObject element)
at Hmi.RegionManager.OnSetRegionNameCallback(DependencyObject element, DependencyPropertyChangedEventArgs args)
at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
[...]

我把c / c稱為30/40其他錯誤行,但我不認為它有用...

當你說你的構造函數引用另一個對象時,你的意思是你應該將它作為參數傳遞給構造函數嗎? 如果是這樣,那么Activator.CreateInstance會出現重載,允許您指定參數值。 有關詳細信息,請參閱MSDN ,但基本上,您可以在類型后添加它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM