How to implement an automatic property method in the .Net Framework

I have a Foo class with many properties:

public class Foo { public int Property1 { get; set; } public int Property2 { get; set; } public int Property3 { get; set; } } 

In another class, I have some method like

 public void SomeMethod() { //... } 

How to insert this method for each property set in the Foo class? I am using .Net Framework 2.0

+2
source share
3 answers

I found an easy way to do this. I am using EasyProp which uses Castle DynamicProxy

My class:

 [AfterPropertySetFilter(typeof(NotifyPropertyChanged))] public class Foo : INotifyPropertyChanged { public virtual int Property1 { get; set; } public virtual int Property2 { get; set; } public virtual int Property3 { get; set; } public event PropertyChangedEventHandler PropertyChanged; } 

Usage example:

  EasyPropBuilder epb=new EasyPropBuilder(); Foo foo = epb.Build<Foo>(); foo.Property1 = 1; foo.PropertyChanged += OnPropertyChanged; foo.Property1 = 2; 

You also need to add a method like this:

 public static void OnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) { Console.WriteLine("Property Changed: " + propertyChangedEventArgs.PropertyName); } 
0
source

I don’t think there is a way to do this at runtime with reflection. What you probably want to do is use the AOP (aspect-oriented) approach, but this is also not supported by the .NET platform. You can use PostSharp if you don't mind using a compiler extension, or look at Unity2 to do AOP .

Edit: You can also consider Castle DynamicProxy . Or, if you have a clear understanding of DynamicMethods and IL code, you can create your own proxy generator class.

However, I think that in most cases you will have to properly encode the rest of your application for proxy processing. In other words, instead of executing:

 Foo f = new Foo(); f.Property1 = 123; 

You would need to do something like:

 Foo f = Generator.GetProxy<Foo>(); // this code is fake. just indicates that you need to get an instance of Foo from a proxy generator, be it DynamicProxy or Unity or whatever. f.Property1 = 123; 
+4
source

You can use the int class extension here. Or some data sets your getter / setter properties.

for instance

 public class Foo { public int Property1 { get; set; } public int Property2 { get; set; } public int Property3 { get; set; } } 

The extension method will look like this:

 public static class IntExtension { public static void SomeMethod(this int property) { // ... } } 

See the following article to use it with .NET 2.0. It is required that you use VisualStudio that supports C # 3.0, but it will still work with the output environment as C # 2.0

Extension Method in C # 2.0

0
source

Source: https://habr.com/ru/post/1333826/


All Articles