请想象在一个类中有以下两个属性:
public string Category { get; set; }
public string DisplayCategory => "SomeCategory"
现在我只想收集所有没有计算属性的PropertyInfo
对象
var properties = type.GetProperties();
var serializables = properties.Where(p => p.CanRead, true));
我如何通过Reflection
发现如果一个属性是一个计算的,所以我可以忽略它?
我想这样做的原因是因为我使用Expression Trees
来自动创建通过Entity Framework 6
处理的查询。实体框架仅为非计算属性创建列,因此无法查询计算属性。
参见本文
下面的方法对我很有效。
我试着看看我是否能找到计算属性和没有Set方法的属性之间的区别:
public int Computed => 2;
public int NoSet { get; }
PropertyInfo.SetMethod
返回null
查看get
方法生成的IL,在NoSet
属性上有CompilerGeneratedAttribute
,但在Computed
属性上没有:
.method public hidebysig specialname instance int32
get_Computed() cil managed
{
.maxstack 8
// [215 32 - 215 33]
IL_0000: ldc.i4.2
IL_0001: ret
}
.method public hidebysig specialname instance int32
get_NoSet() cil managed
{
.custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
= (01 00 00 00 )
.maxstack 8
// [217 28 - 217 32]
IL_0000: ldarg.0 // this
IL_0001: ldfld int32 TestNamespace.TestClass::'<NoSet>k__BackingField'
IL_0006: ret
}
检查变成:
if (property.SetMethod == null && property.GetMethod.GetCustomAttribute(typeof(CompilerGeneratedAttribute)) == null)
return "Computed Property";
我使用delegatedecomcompiler,目前我必须手动将每个计算属性名称添加到自定义配置中。
如果下面的ShouldDecompile方法能自动确定哪些属性应该反编译就好了:
public class CustomDelegateDecompilerConfiguration : Configuration {
public static CustomDelegateDecompilerConfiguration Instance { get; } = new CustomDelegateDecompilerConfiguration();
public static void Enable() => Configuration.Configure(Instance);
public CustomDelegateDecompilerConfiguration() {
RegisterDecompileableMember<Person, string>(x => x.Name);
RegisterDecompileableMembers(typeof(string), nameof(string.IsNullOrWhiteSpace));
RegisterDecompileableMembers(typeof(CustomComputedMethods), new[] {
nameof(CustomComputedMethods.PersonName),
nameof(CustomComputedMethods.MonthInteger),
nameof(CustomComputedMethods.WholeMonthsBetween),
nameof(CustomComputedMethods.WholeYearsBetween)
});
}
public HashSet<MemberInfo> DecompileableMembers { get; } = new HashSet<MemberInfo>();
public override bool ShouldDecompile(MemberInfo memberInfo) => memberInfo.GetCustomAttributes(typeof(DecompileAttribute), true).Length > 0
|| memberInfo.GetCustomAttributes(typeof(ComputedAttribute), true).Length > 0
|| memberInfo.GetCustomAttributes(typeof(CompilerGeneratedAttribute), true).Length > 0
|| DecompileableMembers.Contains(memberInfo)
//*** Would be nice if auto detection was possible with non-existing methods below ***
//|| memberInfo.AutoProperty (One with a backing field automatically generated by the compiler)
//|| memberInfo.HasExpressionBody (One implemented using the => (lambda) syntax)
//|| memberInfo.HasFunctionBody (One implemented using the normal {...} syntax)
;
public override void RegisterDecompileableMember(MemberInfo prop) => DecompileableMembers.Add(prop);
public void RegisterDecompileableMember<T, TResult>(Expression<Func<T, TResult>> expression) where T : class => RegisterDecompileableMember(expression.Body.GetMemberInfo());
public void RegisterDecompileableMembers(Type type, params string[] memberNames) {
foreach(var tmi in type.GetMembers().Where(mi => memberNames.Contains(mi.Name))) {
DecompileableMembers.Add(tmi);
}
}
public void RegisterDecompileableMembers<T>(params string[] memberNames) where T : class => RegisterDecompileableMembers(typeof(T), memberNames);
}
一个示例类:
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public string AlternativeFirstName { get; set; }
public string Name => string.Concat(AlternativeFirstName == string.Empty ? FirstName : AlternativeFirstName, " ", LastName);
}
一些示例扩展方法:
public static class CustomComputedMethods {
public static string PersonName(string firstName, string lastName, string knownAs) => (knownAs ?? firstName).Trim() + " " + lastName.Trim();
public static long MonthInteger(this DateTime d) => checked(d.Year * 12 + d.Month);
public static int WholeMonthsBetween(this DateTime d, DateTime maxDate) => (int)(maxDate.MonthInteger() - d.MonthInteger() - (d.Day > maxDate.Day ? 1 : 0));
public static int WholeYearsBetween(this DateTime d, DateTime maxDate) => d.WholeMonthsBetween(maxDate) / 12;
}