C# Property System

淺唱寂寞╮ 提交于 2019-12-08 01:30:25

Your best option is to generate a dynamic method at runtime using System.Reflection.Emit. You'll get great performance, and once you have it working right, debugging shouldn't be a problem. (You should be able to depend upon it working, I can't see why not).

I prefer the dynamic method approach because it doesn't depend on code generation at compile time or attribute marking or anything of that sort of thing. You can get it to work on any object and it will work for all public gettable/settable properties for that object.

You can try PostSharp to create those attributes and have the class implement the getter/setter interface. Technically it uses reflection, however it creates assemblies at compile time, so its not the the typical System.Relfection way.

If your main focus is going this remotely, you will still need to setup some sort of web service, or WCF service, in which case you will have a proxy, this proxy can in turn use the mentioned framework to set attributes. Web services inherently use reflection anyway, so there is no way around it.

I think it will be hard to find a good solution that doesn't use DynamicMethod.

As I commented on LorenVS's answer, you can use DynamicMethod indirectly through Expression Trees.

I've implemented a simple delegate generator using expression trees. It's on code.google.com, so you might want to check it out: LateBoundMethodFactory.cs. It's still missing proper documentation, but the code there is well commented (much more than I usually do).

Update: link updated

Just found this while searching for DynamicMethod.

http://msmvps.com/blogs/jon_skeet/archive/2008/08/09/making-reflection-fly-and-exploring-delegates.aspx

Turns out you can create a getter/setter delegate from a PropertyInfo and have near native get/set performance.

If you dont want to register earch property individually, you can go for the following approach..

protected void SetPropertyValue&ltV&gt(string propertyName, V value) { ViewState[propertyName] = value; }

protected V GetPropertyValue&ltV&gt(string propertyName, V nullValue) { //Here nullValue can be string.Empty or true || false or 0 etc.... //the default value we want to return if ViewState[propertyName] is null.... if (ViewState[propertyName] == null) { return nullValue; } return (V)ViewState[propertyName]; }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!