簡體   English   中英

使用反射訪問構造函數

[英]Accessing the constructor by using Reflection

假設類是公共的,構造函數是內部的,如

Public class A
{
    private string text;

    internal A(string submittedText);

    public string StrText { get; }
}

在這種情況下,如何使用反射來訪問構造函數。 到目前為止我做了什么

Type[] pTypes = new Type[1];

pTypes[0] = typeof(object);

object[] argList = new object[1];

argList[0] = "Some Text";


ConstructorInfo c = typeof(A).GetConstructor
                (BindingFlags.NonPublic |
                 BindingFlags.Instance,
                 null,
                 pTypes,
                 null);


A foo = (A)c.Invoke(BindingFlags.NonPublic,
                    null,
                    argList,
                    Application.CurrentCulture);

但是它顯示了一個錯誤。 有什么建議么

我認為該錯誤可能是由GetConstructor引起的,您傳入了Object類型而不是String類型。

var ctr = typeof(A).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(String) }, null);

順便說一句,如果類型A本身是內部的,並且您在同一程序集中知道公共類型B和A,則可以嘗試:

Type typeA = typeof(B).Assembly.GetType("Namespace.AssemblyName.A", false);
var ctr = typeA.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(String) }, null);

嘗試這個:

Type type = typeof(A);

            Type[] argTypes = new Type[] { typeof(String) };

            ConstructorInfo cInfo = type.GetConstructor(argTypes);

            object[] argVals = new object[] { "Some string" };
            Ap = (A)cInfo.Invoke(argVals);

我從該站點獲得了幫助:

http://www.java2s.com/Code/CSharp/Reflection/CallGetConstructortogettheconstructor.htm

我只是在一個示例控制台應用程序上嘗試過,該應用程序具有一個內部類,並且可以正常工作。

namespace ConsoleApplication1
{
    internal class Person
    {
        public Person(string name)
        {
            Name = name;
        }

        public string Name { get; set; }
    }
}

public static void Main()
        {

            Type type = typeof(Person);

            Type[] argTypes = new Type[] { typeof(String) };

            ConstructorInfo cInfo = type.GetConstructor(argTypes);

            object[] argVals = new object[] { "Some string" };
            Person p = (Person)cInfo.Invoke(argVals);
        }

構造函數中的參數類型是字符串,而不是對象。 所以也許像這樣:

pTypes[0] = typeof(string);

您應該使用Activator.CreateInstance

您可以使用object o1 = Activator.CreateInstance(typeof (myclass), true); 用於創建實例。 無需通過復雜的代碼即可使用同一方法創建實例。

暫無
暫無

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

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