用私有构造函数实例化内部类

编程入门 行业动态 更新时间:2024-10-27 08:33:27
本文介绍了用私有构造函数实例化内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

用私有构造函数实例化内部类

本文发布于:2023-11-04 10:08:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557640.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:部类   函数   实例

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!