Created
June 11, 2022 06:51
-
-
Save NikiforovAll/ccbb832e500fec37fc0ec2447474a303 to your computer and use it in GitHub Desktop.
ProtectedView
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; | |
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