开发者

How do I instantiate a class that only has a private parameterless constructor in Silverlight?

开发者 https://www.devze.com 2023-01-17 15:44 出处:网络
I\'m working on a feature request for a .NET test data builder. I need to be able to instantiate classes that only have private parameterless constructors.

I'm working on a feature request for a .NET test data builder. I need to be able to instantiate classes that only have private parameterless constructors.

For instance, I might need to instantiate the following class:

public class MyClass()
{
    private MyClass(){}
}

For most other classes I use the following code:

(T)Activator.CreateInstance(typeof(T), true)

But for classes that only have a 开发者_开发问答private parameterless constructor I use the following:

(T)FormatterServices.GetUninitializedObject(typeof(T))

Unfortunately, I also have the requirement that this work in Silverlight and unfortunately Silverlight doesn't currently contain System.Runtime.Serialization.FormatterServices.

Does anyone know of anything in the Silverlight implementation that would allow me to get around this? Failing that, does anyone know how I might implement my own version of this method?


You can't instantiate that class from outside it. Presumably it's been deliberately designed so that you can't instantiate it.

I'd expect there to be some static way of getting instances, such as a singleton property or a factory method... but if you need to be able to do this with any type, that's not going to work.

Basically, you'll need to rethink your design - don't try to subvert the wishes of the class author.


It turns out, that the answer was right in front of me.

If you have a class defined as follows:

public class MyClass
{
    private MyClass(){}
}

you can instantiate it using the following code which I mentioned in my question:

(T)Activator.CreateInstance(typeof(T), true)

The additional parameter of true, creates an instance using the type's default constructor.

So it turns out, I didn't even need to use FormatterServices.GetUninitializedObject in the first place.

However, I'd like to thank Jon Skeet for his answer because it helped me to question my design and dig a bit deeper into Activator.CreateInstance and increase my understanding of class instantiation a little.

For now, my solution is remove the use of FormatterServices and just allow an exception to be thrown if something goes wrong with the type creation.

Currently, from what I can tell, using (T)Activator.CreateInstance(typeof(T), true) I should be able to construct most classes I've come across except for the following:

public MyClass()
{
    int a;
    private MyClass(int a)
    {
        this.a = a;
    }
}

However, it turns out there is a way suggested here to be able to instantiate this class:

int argA = 100; 
Type type = typeof(MyClass);

ConstructorInfo c = type.GetConstructor(BindingFlags.NonPublic 
| BindingFlags.Instance, null, new Type[] { typeof(int) }, null);

MyClass o = (MyClass)c.Invoke(new Object[] { argA });

But after thinking about what Jon said, I don't think this will be of much use to anyone using the test data builder I'm enhancing. If someone's gone to that much trouble to prevent a class from being instantiated, then perhaps it shouldn't be able to be constructed other than by the means provided by the class designer.


You can do it using reflection, but

  • you should really decide if you are doing the right thing. As others said the class is probably designed not to be instantiated that way. I understand however that in some rare cases this may be required.

  • you need to run this in full trust, i.e. out of the browser. You cannot do it inside the browser.

Here's the code:

var privateConstructors = typeof(MyClass).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var constr in privateConstructors)
{
    var obj = constr.Invoke(new object[0]);
    return;
}
throw new Exception("private constructor not found");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号