簡體   English   中英

C#Activator.CreateInstance通用實例丟失

[英]C# Activator.CreateInstance generic instance getting lost

僅供參考:冗長的序言是為了幫助解釋為什么我使用Activator.CreateInstance 我有多個實體(包含與數據庫列信息相對應的對象),這些實體“包含”在多個數據庫中,每個實體具有不同的表/列設置。 因此,我能夠從每個數據庫檢索實體,但是每個數據庫檢索實體的方式不同。 數據庫類型直到運行時才知道,並且在整個執行過程中可能會有所不同。 我創建了以下設置:

首先定義每個實體應支持的查詢操作,每個實體讀取器應支持這些操作。

public abstract class Operations<T> {
    public delegate T findDelegate(int id);
    public findDelegate find;
}

// there are many of these N=1,2,..., but here is one
// use abstract class since implementation of queries should be done by handlers
public class EntityNReader : Operations<EntityN> {
    public Reader();
}

為“ Handler”類定義一個接口,即這些類實現上面列出的查詢操作。

public interface IHandler<T> {
    public string find(int id);
}

// there are many of these N,M=1,2..., but here is one
// use of interface is to force handlers to implement all query types
public class EntityNHandlerForDbTypeM : IHandler<EntityN> {
    public string find(int id) {/*whatever*/}
}

這使得開發人員能夠創建一個類來處理EntityN查詢操作的DbTypeM 現在,創建一個包含讀取器對象的Database類,並將處理程序方法綁定到讀取器委托。

public class Database {
    // there are many of these, but here is one
    public EntityNReader EntitiesN;

    public Database(string dbType) {
        // this is called for each EntityNReader
        bindHandlers<Reader, TypeN>(MyReader, dbType);
        // ...

        // nullreferenceexception
        EntitiesN.find(0);
    }

    // this is a factory that also performs late binding
    private void bindHandlers<T,K>(T reader, string dbTypeM)
        where T: Operations<K>, new()
    {
        // create instance of EntityNReader
        r = (T)Activator.CreateInstance(typeof(T));
        // r != null

        // create instance of handler
        IHandler<K> h = (IHandler<K>)(Activator.CreateInstance(
            Type.GetType("namespace.to.EntityNHandlerForDbTypeM"),
            new object[] { this }
        ));

        // bind delegates
        r.find = h.find;
    }
}

正如您在Database的構造函數中所看到的那樣,現在編寫代碼的方式是,即使創建了EntityNReader實例r並且(驗證為)不為null,我仍然得到了NullReferenceException

但是,如果我在Database而不是在bindHandlers實例化EntitiesN ,則代碼將編譯並且一切正常。 我不只是這樣做的原因是(隨后)我想在實例化Database類時bindHandlersbindHandlers內部創建讀取器/處理程序。

這是怎么回事 必要時鏈接到實際代碼。 PS我對編程還比較陌生,因此我很樂意聽取經驗豐富的開發人員如何設計此組件的信息(特別是如果我走錯了路的話)。

我意識到您的代碼只是示例,但我馬上發現了這一點...

if (supports[typeof(Entity1).Name]) { bindHandlers<Entity1Reader, Entity1>(Entities1, CamaDbType); }
if (supports[typeof(Entity2).Name]) { bindHandlers<Entity1Reader, Entity1>(Entities1, CamaDbType); }

您是否可能有一個簡單的復制/粘貼錯誤? 注意,兩個bindHandlers調用都傳入了Entities1。

暫無
暫無

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

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