开发者

Library development - looking for valid use cases for suggested feature

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.


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜