Last active
February 24, 2025 02:37
-
-
Save jnm2/96cd9d1d142cd66cbddfd63da73cb488 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Reflection; | |
internal static class ReflectionUtils | |
{ | |
public static bool IsVisibleOutsideAssembly(Type type) | |
{ | |
return (type.Attributes & TypeAttributes.VisibilityMask) switch | |
{ | |
TypeAttributes.Public => true, | |
TypeAttributes.NestedFamily or TypeAttributes.NestedFamORAssem => IsVisibleOutsideAssembly(type.DeclaringType!), | |
_ => false, | |
}; | |
} | |
public static bool IsVisibleOutsideAssembly(MethodInfo method, bool assumeDeclaringTypeIsVisibleOutsideAssembly = false) | |
{ | |
return (method.Attributes & MethodAttributes.MemberAccessMask) switch | |
{ | |
MethodAttributes.Public or MethodAttributes.Family or MethodAttributes.FamORAssem => | |
assumeDeclaringTypeIsVisibleOutsideAssembly || IsVisibleOutsideAssembly(method.DeclaringType!), | |
_ => false, | |
}; | |
} | |
public static bool IsInitOnly(MethodInfo method) | |
{ | |
return method.ReturnParameter.GetRequiredCustomModifiers().Any(m => m.FullName == typeof(IsExternalInit).FullName!); | |
} | |
public static bool IsReadOnly(MethodInfo method) | |
{ | |
return HasAttribute(method, typeof(IsReadOnlyAttribute).FullName!); | |
} | |
public static bool IsReadOnly(Type type) | |
{ | |
return HasAttribute(type, typeof(IsReadOnlyAttribute).FullName!); | |
} | |
private static bool HasAttribute(MemberInfo member, string attributeFullName) | |
{ | |
return member.GetCustomAttributesData().Any(d => d.AttributeType.FullName == attributeFullName); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment