如何在 C# 中使用私有构造函数实例化对象? [英] How to instantiate an object with a private constructor in C#?

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

问题描述

我绝对记得在某处看到过使用反射或其他方法这样做的示例.这与 SqlParameterCollection 有关系,它不是由用户创建的(如果我没记错的话).可惜再也找不到了.

I definitely remember seeing somewhere an example of doing so using reflection or something. It was something that had to do with SqlParameterCollection which is not creatable by a user (if I'm not mistaken). Unfortunately cannot find it any longer.

有人可以在这里分享这个技巧吗?并不是说我认为这是一种有效的开发方法,我只是对这样做的可能性非常感兴趣.

Can anyone please share this trick here? Not that I consider it a valid approach in development, I'm just very interested in the possibility of doing this.

推荐答案

// the types of the constructor parameters, in order
// use an empty Type[] array if the constructor takes no parameters
Type[] paramTypes = new Type[] { typeof(string), typeof(int) };

// the values of the constructor parameters, in order
// use an empty object[] array if the constructor takes no parameters
object[] paramValues = new object[] { "test", 42 };

TheTypeYouWantToInstantiate instance =
    Construct<TheTypeYouWantToInstantiate>(paramTypes, paramValues);

// ...

public static T Construct<T>(Type[] paramTypes, object[] paramValues)
{
    Type t = typeof(T);

    ConstructorInfo ci = t.GetConstructor(
        BindingFlags.Instance | BindingFlags.NonPublic,
        null, paramTypes, null);

    return (T)ci.Invoke(paramValues);
}

这篇关于如何在 C# 中使用私有构造函数实例化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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