簡體   English   中英

如何使用反射創建以接口為構造函數參數的類實例?

[英]How to create an instance of class that takes interface as its constructor parameter using reflection?

object[] parame = new object[1];
parameters[0] = param1;

ConstructorInfo[] info = type.GetConstructors();
info[0].Invoke(parame );

obj= Activator.CreateInstance(type, parameters);

這給了我錯誤說ctor沒有找到,因為ctor需要接口作為參數。

現在如何創建該對象的實例?

public Controller(ICustomInterface custom)
        {
            _custom= custom;
        }

我試圖用相同的參數調用ctor,它說此類的對象無法轉換為Interface類型。 雖然此類表示該接口。

具有接口的實現,以便您可以創建實現接口的實例,如下所示:

class CustomClass : ICustomInterface {}

您只需將Activator稱為

var obj = Activator.CreateInstance(typeof(Controller), new CustomClass());

它會返回一個正確的實例Contoller ,與new CustomClass()傳遞的構造函數參數

暫無
暫無

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

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