Skip to content

Instantly share code, notes, and snippets.

@NikiforovAll
Created June 11, 2022 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NikiforovAll/ccbb832e500fec37fc0ec2447474a303 to your computer and use it in GitHub Desktop.
Save NikiforovAll/ccbb832e500fec37fc0ec2447474a303 to your computer and use it in GitHub Desktop.
ProtectedView
using System.Reflection;
namespace ProtectedViews;
public class ProtectedView
{
private readonly ISet<string> denyList;
public ProtectedView(params string[] fields)
{
denyList = new HashSet<string>(
fields, StringComparer.InvariantCultureIgnoreCase);
}
public ProtectedView Exclude(params string[] fields)
{
foreach (var f in fields)
{
denyList.Add(f);
}
return this;
}
public IDictionary<string, object?> ToView<T>(T source) =>
PropertyInfoFactory.Create<T>()
.Where(p => !denyList.Contains(p.Name))
.ToDictionary(p => p.Name, p => p.GetValue(source));
}
public static class PropertyInfoFactory
{
public static PropertyInfo[] Create<T>() => PropertyInfoCache<T>.Instance;
private static class PropertyInfoCache<T>
{
public static readonly PropertyInfo[] Instance =
typeof(T).GetProperties(BindingFlags.DeclaredOnly
| BindingFlags.Public
| BindingFlags.Instance);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment