Fastmember access to non-public properties
I wanted to replace the reflection index helper module with FastMember ( https://www.nuget.org/packages/FastMember/ ) but came across the following problem.
I have the following setup:
class Program
{
static void Main(string[] args)
{
var d = new DerivedClass
{
Name = "Derived Name Property",
BaseName = "Base Name Property",
BaseInternalName = "Base Internal Name Property",
};
Console.WriteLine(d["Name"]);
Console.WriteLine(d["BaseName"]);
Console.WriteLine(d["BaseInternalName"]);
Console.ReadLine();
}
}
public abstract class BaseClass
{
public object this[string propertyName]
{
get
{
var x = GetTypeAccessor();
return x[this, propertyName];
}
set
{
var x = GetTypeAccessor();
x[this, propertyName] = value;
}
}
protected abstract TypeAccessor GetTypeAccessor();
public string BaseName { get; set; }
internal string BaseInternalName { get; set; }
}
public class DerivedClass : BaseClass
{
public string Name { get; set; }
private TypeAccessor _typeAccessor;
protected override TypeAccessor GetTypeAccessor()
{
if (_typeAccessor == null)
_typeAccessor = TypeAccessor.Create(this.GetType(), true);
return _typeAccessor;
}
}
With this, I get the following exception: in the line Console.WriteLine(d["BaseInternalName"]);
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in FastMember_dynamic
Innerexception is null.
According to nuget https://www.nuget.org/packages/FastMember/ there should be support for accessing non-public properties since version 1.0.0.8:
- 1.0.0.8 - provide support for non-public accessories (at least I think that's the point)
Another thing I noticed is that nuget says 1.0.0.11 is the newest version, but the DLL I download to my machine on Install-Package FastMember
is version 1.0.0.9, probably marc https://stackoverflow.com / users / 23354 / marc-gravell sees this and can fix it. :)
source to share
Digging into the code inside TypeAccessor
(more precisely, in a derivative DelegateAccessor
), you can see what is allowNonPublicAccessors
used as a value to get a non-public property of the getter / setter , not a non-public property / field.
This is the relevant piece of code (inside TypeAccessor.WriteMapImpl
):
PropertyInfo prop = (PropertyInfo)member;
MethodInfo accessor;
if (prop.CanRead && (accessor = (isGet ? prop.GetGetMethod(allowNonPublicAccessors) : prop.GetSetMethod(allowNonPublicAccessors))) != null)
Also, you can see what is CreateNew
trying to access the fields / properties of the open instance:
PropertyInfo[] props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
Hence, you cannot access any non-public fields / properties using an object TypeAccessor
.
source to share