![](/img/trans.png)
[英]Is it possible to create a generic factory with constructor with parameters using Activator.CreateInstance()?
[英]Is it possible to CreateInstance of object with protected constructor?
各位小伙伴大家好,問題是這樣的:
public abstract class BaseClass
{
protected BaseClass()
{
// some logic here
}
protected BaseClass(Object parameter) : this()
{
// some more logic
}
}
public class Descendant : BaseClass
{
// no constructors
}
我試圖在后代 class 上調用Activator.CreateInstance ,但未找到構造函數。
我是否需要在 Descentant class 上明確定義它?
我使用的綁定是這些: BindingFlags.Instance | BindingFlags.NonPublic
BindingFlags.Instance | BindingFlags.NonPublic
注意 1 :我實際上是在調用 AppDomain.CreateInstanceAndUnwrap() ,如果它應該有一些影響的話。
domain.CreateInstanceAndUnwrap(path, typeName, false, BindingFlags.Instance |
BindingFlags.NonPublic, null, new[] { parameter }, null, null);
注意 2 :如果我在后代 class 中顯式定義受保護的構造函數,那么它就可以工作,但我想盡可能避免這種情況。
您不能使用 Activator.CreateInstance,但在 Full Trust 環境中,您應該能夠通過反射直接定位並調用構造函數。
實際上,您的后代 class 會自動提供一個公共構造函數,該構造函數會傳遞給基類 class 的受保護構造函數。這應該可以正常工作:
Activator.CreateInstance(typeof(Descendant))
好的,現在我意識到您正在嘗試調用非默認構造函數。 不幸的是,這是不允許的。 直接調用基類 class 的構造函數是行不通的,因為基類 class 是抽象的。 您需要在后代 class 上有一個構造函數(自動生成或顯式定義)才能構造 object。
您可以在后代 class 上創建一個傳遞構造函數,但您的評論聽起來像是您試圖避免強制實施者在其構造函數中傳遞一個值。 您可能真正想要的是一個可以在構造 object 之后調用的初始化方法:
// Define other methods and classes here public abstract class BaseClass { protected BaseClass() { // some logic here } protected Object Parameter {get; private set;} public virtual void Initialize(Object parameter) { Parameter = _parameter; // some more logic } }
您在這里想要的似乎是構建器模式,而不是構造函數。 這很簡單——您定義一個 class(帶有默認構造函數)來“構建”您想要的 class。 像這樣的東西(注意:前面未經測試的代碼):
public abstract class BaseBuildable : MarshalByRefObject {
public String Foo { get; internal set; }
}
public class DerivedBuildable : BaseBuildable { }
public class BuildableBuilder : MarshalByRefObject {
private String _foo;
public BuildableBuilder WithFoo(String foo) { _foo = foo; return this; }
public TBuildable Build<TBuildable>() where TBuildable : BaseBuildable, new() {
return new TBuildable { Foo = _foo; }
}
}
// Used so:
var builder = domain.CreateInstanceAndUnwrap(.. // yadda yadda, you want a BuildableBuilder
var buildable = builder.WithFoo("Foo, yo").Build();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.