internal static object SecureCreateInstance(Type type, object[] args, bool allowNonPublic) {
if (type == null) {
throw new ArgumentNullException("type");
}
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;
// 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 instantiate a public type in *our* assembly, but does not
// have full reflection permission. We shouldn't pass BindingFlags.NonPublic in this case.
// The reason we don't directly demand the permission here is because we don't know whether
// a public nr non-public .ctor will be invoked. We want to allow the public .ctor case to
// succeed.
allowNonPublic = false;
}
}
if (allowNonPublic) {
flags |= BindingFlags.NonPublic;
}
return Activator.CreateInstance(type, flags, null, args, null);
}