我正在尝试使用反射来创建类的实例。但它是内部密封的并且有私有构造函数。我想知道如何初始化它,并且作为框架的一部分,我只能使用反射将其取出?
internal sealed class ABC
{
private ABC(string password){}
public static ABC Create(string password){};
}
添加:
System.ServiceModel.Channels.SelfSignedCertificate 是我尝试使用的内部类
编辑:我没有注意到您提到您尝试初始化的类型是.NET 框架的一部分。我以为这是你自己的类型之一,只是从其他地方引用的。
我强烈敦促你不要尝试这个。 Microsoft 完全可以自由地在框架版本之间更改或删除内部类 - 如果您依赖这样的实现细节,您的代码将非常脆弱。
更改您的设计以避免需要这样做。
原答案:
是的,你必须使用反射 - 像这样:
using System;
using System.Reflection;
internal sealed class ABC
{
private ABC(string password)
{
Console.WriteLine("Constructor called");
}
}
public class Test
{
static void Main()
{
ConstructorInfo ctor = typeof(ABC).GetConstructors
(BindingFlags.Instance | BindingFlags.NonPublic)[0];
ABC abc = (ABC) ctor.Invoke(new object[] { "test" });
}
}
请注意,以这种方式违反访问修饰符需要ReflectionPermissionFlag.MemberAccess
允许。如果你知道会有一个名为的静态方法Create
,你最好调用that通过反射:
using System;
using System.Reflection;
internal sealed class ABC
{
private ABC(string password)
{
Console.WriteLine("Constructor called");
}
public static ABC Create(string password)
{
return new ABC(password);
}
}
public class Test
{
static void Main()
{
MethodInfo method = typeof(ABC).GetMethod("Create",
BindingFlags.Static | BindingFlags.Public);
ABC abc = (ABC) method.Invoke(null, new object[]{"test"});
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)