簡體   English   中英

使用反射在內部類中使用參數實例化構造函數

[英]Instantiating a constructor with parameters in an internal class with reflection

我有類似的東西:

object[] parameter = new object[1];
parameter[0] = x;
object instantiatedType =
Activator.CreateInstance(typeToInstantiate, parameter);

internal class xxx : ICompare<Type>
{
    private object[] x;

    # region Constructors

    internal xxx(object[] x)
    {
        this.x = x;
    }

    internal xxx()
    {
    }

    ...
}

我得到:

拋出異常:System.MissingMethodException:找不到類型為“xxxx.xxx”的構造函數..

有任何想法嗎?

問題是Activator.CreateInstance(Type, object[])不考慮非公共構造函數。

例外

MissingMethodException:找不到匹配的公共構造函數。

通過將構造函數更改為public可見性可以很容易地顯示出來; 然后代碼正常工作。

這是一個解決方法(已測試):

 BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
 CultureInfo culture = null; // use InvariantCulture or other if you prefer
 object instantiatedType =   
   Activator.CreateInstance(typeToInstantiate, flags, null, parameter, culture);

如果您只需要無參數構造函數,那么它也可以工作:

//using the overload: public static object CreateInstance(Type type, bool nonPublic)
object instantiatedType = Activator.CreateInstance(typeToInstantiate, true)

(測試成功)

object instantiatedType =
   Activator.CreateInstance(typeToInstantiate,
   System.Reflection.BindingFlags.NonPublic |
     System.Reflection.BindingFlags.Instance,
   null, new object[] {parameter}, null);

這有兩個問題:

  • new object[] {parameter}幫助它處理傳遞object[]作為方法的單個參數的問題,該方法接受params object[]參數
  • BindingFlags有助於解析非公共構造函數

(這兩個null綁定器有關 ;默認綁定器行為適用於我們想要的)

您需要調用Activator.CreateInstance的不同重載,以允許您傳遞nonPublicBindingFlags參數。

我發現所有這些CreateInstance重載都很笨拙; 我更喜歡做的是:

  1. 調用typeToInstantiate.GetConstructor() ,傳遞BindingFlags.NonPublic
  2. 調用ConstructorInfo.Invoke ,向其傳遞構造函數參數

改為

Activator.CreateInstance(typeToInstantiate,new object[] { parameter });

這是因為您的構造函數還期望對象數組和激活器已將其拆分為單獨的對象

暫無
暫無

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

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