如何调用 protected 构造函数?
public class Foo{
public Foo(a lot of arguments){}
protected Foo(){}
}
var foo=???
这显然没有通过测试:
public class FooMock:Foo{}
var foo=new FooMock();
Assert(typeof(Foo), foo.GetType());
最佳答案
调用无参数保护/私有(private)构造函数:
Foo foo = (Foo)Activator.CreateInstance(typeof(Foo), true);
调用带参数的非公共(public)构造函数:
var foo = (Foo)typeof(Foo)
.GetConstructor(
BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance,
null,
new[] { typeof(double) },
null
)
.Invoke(new object[] { 1.0 });
class Foo
{
private Foo(double x){...}
}
关于c# - 如何在 C# 中调用 protected 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4365745/