库开发 - 寻找建议功能的有效用例

发布于 2024-08-26 20:26:31 字数 965 浏览 15 评论 0原文

我正在为一个名为 Fasterflect 的库做出贡献,其目的是“改善开发人员使用反射的体验”。因此,它提供了构建在经典反射之上的抽象,并且可以在完全相同的场景中使用。

下面显示了通过对象实例访问成员的当前语法:

obj.SetPropertyValue( "PropertyWithPrivateSetter", "foo" );
obj.SetFieldValue( "_readOnlyIntegerProperty", 123 );

一位用户建议我们添加对基于 lamdba 的访问的支持(类似于 Fluent Hibernate):

obj.SetPropertyValue<MyClass>( x => x.PropertyWithPrivateSetter, "foo" );
obj.SetFieldValue<MyClass>( x => x.ReadOnlyInteger, Access.CamelCaseField(Prefix.Underscore), 123 );

我很难想象这会有用的场景,鉴于反射通常是在编译时不知道的类型上执行的。我只是缺乏想象力吗?在编译时知道类型的情况下,是否存在有效的反射场景?

此 NBuilder 功能请求,您还可以查看 Fasterflect 功能请求

I'm contributing to a library called Fasterflect whose purpose is "improving the developer experience of using reflection". As such, it provides an abstraction built on top of classic reflection and would be used in exactly the same scenarios.

The following shows the current syntax for accessing members via an object instance:

obj.SetPropertyValue( "PropertyWithPrivateSetter", "foo" );
obj.SetFieldValue( "_readOnlyIntegerProperty", 123 );

One user has suggested that we add support for lamdba-based access (similar to Fluent Hibernate):

obj.SetPropertyValue<MyClass>( x => x.PropertyWithPrivateSetter, "foo" );
obj.SetFieldValue<MyClass>( x => x.ReadOnlyInteger, Access.CamelCaseField(Prefix.Underscore), 123 );

I'm having a hard time thinking of scenarios where this would be useful, given that reflection is usually performed on types that you do not know about at compile-time. Am I just lacking in imagination? Are there valid scenarios for reflection where you know the type at compile-time?

There is some additional context for the original suggestion at this NBuilder feature request and you can also view the Fasterflect feature request.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

与之呼应 2024-09-02 20:26:31

主要使用场景是您所描述的场景:具有公共 getter 但私有 setter 的属性。通过使用 lambda 表达式,您可以提供属性名称的编译时检查(即:没有魔术字符串),但仍然提供一种通过反射设置“只读”属性的方法。

The main usage scenario would be the one you describe: A property with a public getter, but private setter. By using lambda expressions, you provide compile time checking of the property name (ie: no magic strings), but still provide a way to set a "read only" property via reflection.

帅气称霸 2024-09-02 20:26:31

扩展里德所说的(他说的比我输入的更简洁)一个非常有效的场景是“只读工厂”,它生产出提供真正的只读上下文或提供读取设置的包装器-仅限对象并避免构造函数设置(即真正的密封类)。

To extend on what Reed said (who said it more succinctly than what I had typed) one very valid scenario for this is for "read-only factories" which churn out wrappers providing either true read-only contexts or provide set-up of read-only objects and avoid constructor setup (i.e. true sealed classes).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文