The Type
class is reflection. You can do:
Type theType = myobject.GetType(); // if you have an instance
// or
Type theType = typeof(MyObject); // if you know the type
var constructor = theType.GetConstructor(Type.EmptyTypes);
It will return null if a parameterless constructor does not exist.
If you also want to find private constructors, use the slightly longer:
var constructor = theType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null, Type.EmptyTypes, null);
There's a caveat for value types, which aren't allowed to have a default constructor. You can check if you have a value type using the Type.IsValueType
property, and create instances using Activator.CreateInstance(Type)
;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…