用私有构造函数实例化内部类 [英] Instantiating Internal class with private constructor

查看:131
本文介绍了用私有构造函数实例化内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用反射来创建类的实例。但是它是内部密封的,具有私有构造函数。我不知道如何初始化它,并且作为框架的一部分,我只能使用反射将其取出?

I am trying to use reflection to create instance of a class. But it is sealed internal and has private constructor. I wonder how can i initiaise it and as its part of framework, I can only use reflection to take it out?

internal sealed class ABC
{
    private ABC(string password){}
    public static ABC Create(string password){};
}

添加:
System.ServiceModel.Channels.SelfSignedCertificate是内部的我正在尝试使用的类

Added: System.ServiceModel.Channels.SelfSignedCertificate is the internal class I am trying to use

推荐答案

首先,它是内部的事实意味着您不应被认为是做你想做的事。

First of all, the very fact that it is internal means you're not supposed to be doing what you want to do.

你应该认真尝试寻找一条通往你想完成的事情的替代路线。

You should seriously try to find an alternate route to what you want to accomplish.

不幸的是,您没有告诉我们您想要完成的工作,只是告诉您您想完成的下一步,因此我可以为您提供帮助。

Unfortunately, you don't tell us what you want to accomplish, only the next step you think you want to do, so that's what I can help you with.

此代码将起作用,并访问公共静态方法:

This code will work, and accesses the public static method:

Type t = typeof(SomeOtherTypeInSameAssembly)
    .Assembly.GetType("ClassLibrary1.ABC");
MethodInfo method = t.GetMethod("Create",
    BindingFlags.Public | BindingFlags.Static, null,
    new Type[] { typeof(String) },
    new ParameterModifier[0]);
Object o = method.Invoke(null, new Object[] { "test" });

请注意,这依赖于访问同一程序集中的另一种类型,即公共类型。如果没有,则需要掌握包含类型的Assembly对象。

Note that this relies on having access to another type in the same assembly, that is public. If you don't have that, you need to get hold of the Assembly object that contains the type.

这篇关于用私有构造函数实例化内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆