gpt4 book ai didi

c# - Fastmember 访问非公共(public)属性

转载 作者:行者123 更新时间:2023-11-30 16:57:18 24 4
gpt4 key购买 nike

我想用 FastMember ( https://www.nuget.org/packages/FastMember/ ) 替换我的反射索引访问器,但偶然发现了以下问题。

我有以下设置:

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;
}
}

有了这个,我在行 Console.WriteLine(d["BaseInternalName"]);

上得到以下异常

“System.ArgumentOutOfRangeException”类型的未处理异常发生在 FastMember_dynamic 中

Innerexception 为空。

根据 nuget https://www.nuget.org/packages/FastMember/从 1.0.0.8 版本开始,应该支持访问非公共(public)属性:

  • 1.0.0.8 - 为非公共(public)访问者提供支持(至少我认为是这个意思)

我注意到的另一件事是,在 nuget 中它说 1.0.0.11 是最新版本,但是通过 Install-Package FastMember 下载到我的计算机的 dll 版本为 1.0.0.9 , 也许马克 https://stackoverflow.com/users/23354/marc-gravell看到这个并可以修复它。 :)

最佳答案

深入研究 TypeAccessor 中的代码(或者更准确地说是派生的 DelegateAccessor),您可以看到使用了 allowNonPublicAccessors 作为获取非公共(public)属性 getter/setter 的值,而不是非公共(public)属性/字段。

这是相关的代码片段(在 TypeAccessor.WriteMapImpl 内):

PropertyInfo prop = (PropertyInfo)member;
MethodInfo accessor;
if (prop.CanRead && (accessor = (isGet ? prop.GetGetMethod(allowNonPublicAccessors) : prop.GetSetMethod(allowNonPublicAccessors))) != null)

此外,您还可以看到 CreateNew 仅尝试访问公共(public)实例字段/属性:

PropertyInfo[] props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public);

因此,您不能通过 TypeAccessor 对象访问任何非公共(public)字段/属性。

关于c# - Fastmember 访问非公共(public)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26803788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com