internal static object SecureConstructorInvoke(Type type, Type[] argTypes, object[] args,
bool allowNonPublic, BindingFlags extraFlags) {
if (type == null) {
throw new ArgumentNullException("type");
}
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | extraFlags;
// The only case we need to worry about is when the type is in the same assembly
// as us. In all other cases, reflection will take care of security.
if (type.Assembly == typeof(SecurityUtils).Assembly) {
// if it's an internal type, we demand reflection permission.
if (!(type.IsPublic || type.IsNestedPublic)) {
(new ReflectionPermission(PermissionState.Unrestricted)).Demand();
}
else if (allowNonPublic && !HasReflectionPermission) {
// Someone is trying to invoke a ctor on a public type in *our* assembly, but does not
// have full reflection permission. We shouldn't pass BindingFlags.NonPublic in this case.
allowNonPublic = false;
}
}
if (allowNonPublic) {
flags |= BindingFlags.NonPublic;
}
ConstructorInfo ctor = type.GetConstructor(flags, null, argTypes, null);
if (ctor != null) {
return ctor.Invoke(args);
}
return null;
}
}