![](/img/trans.png)
[英]Activator.CreateInstance calling constructor with class as parameter
[英]Activator.CreateInstance with private sealed class
我正在嘗試新建一個 LocalCommand 實例,它是 System.Data.SqlClient.SqlCommandSet 的私有類。 我似乎能夠很好地獲取類型信息:
Assembly sysData = Assembly.Load("System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
localCmdType = sysData.GetType("System.Data.SqlClient.SqlCommandSet+LocalCommand");
但是當我嘗試實例化它時 Activator.CreateInstance 拋出異常:
object item = Activator.CreateInstance(localCmdType,
new object[] { commandText, parameters, num7, commandType });
System.MissingMethodException:未找到類型“System.Data.SqlClient.SqlCommandSet+LocalCommand”的構造函數。
構造函數參數與我在 Reflector 中看到的簽名相匹配。 是新建一個私有類,內部 ctor 支持不同的 CreateInstance 重載還是什么?
我的第一個想法是使用ConstructorInfo constructorInfo = Type.GetConstructor()
獲取ConstructorInfo
,然后是constructorInfo.Invoke()
。 我懷疑Activator.CreateInstance
很難調用您通常無法訪問的構造函數,盡管我不記得自己嘗試過。
我讓它以這種方式工作:
using System;
using System.Reflection;
class Test
{
public String X { get; set; }
Test(String x)
{
this.X = x;
}
}
class Program
{
static void Main()
{
Type type = typeof(Test);
ConstructorInfo c = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,
null, new Type[] { typeof(String) }, null);
Object o = c.Invoke(new Object[] { "foo" });
}
}
訣竅是專門用GetConstructor
構造函數,而不是嘗試在GetConstructors
的結果中找到它。 去搞清楚。
我的回復可能有點晚了,但我遇到了一個適合這個主題的類似問題。
我想使用Activator.CreateInstance
實例化一個非公共構造函數並傳遞它的參數。
public class Node
{
string name;
Node parent;
protected Node(string name,Node parent)
{
this.name = name;
this.parent = parent;
}
public static Node Create(string name,Node parent)
{
Node result = Activator.CreateInstance(
type: typeof(Node),
bindingAttr: BindingFlags.Instance | BindingFlags.NonPublic,
binder: null, //default binder
args: new object[] { name, parent },
culture: null);
return (Node)result;
}
}
棘手的部分是綁定標志。
我的第一直覺是使用BindingFlags.CreateInstance | BindingFlags.NonPublic
BindingFlags.CreateInstance | BindingFlags.NonPublic
,但是這導致拋出異常:未找到類型“節點”上的 MissingMethodException 構造函數。
技巧是確保使用正確的CreateInstance
重載:
// WRONG
... Activator.CreateInstance(
type,
BindingFlags.Instance
| BindingFlags.NonPublic
);
這將調用params
重載,默認為Instance | Public | CreateInstance
Instance | Public | CreateInstance
Instance | Public | CreateInstance
,並且您的綁定標志將作為參數傳遞給構造函數,給出模糊的MissingMethodException
。
另外,使用Instance | Public | NonPublic
Instance | Public | NonPublic
Instance | Public | NonPublic
如果您不確定構造函數的可見性:
// right
... Activator.CreateInstance(
type,
BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic,
null,
new object[] { }, // or your actual constructor arguments
null
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.