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

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

问题描述

我试图使用反射来创建一个类的实例。但它是密封的内部和具有私有的构造。我不知道如何可以initiaise它和框架的其本身而言,我只能用反射把它拿出来?

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.

这code将工作,并访问公共静态方法:

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" });

请注意,这依赖于有机会获得另一种类型的同一程序,这是公开的。如果没有这一点,你需要获得包含该类型的对象大会的举行。

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.

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

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