I have a class with some properties, eg
public class Foo {
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
Now I want to have copy of Foo, while applying some operations on certain properties.
I could do a new method like so:
public static Foo ReplaceSomethingInFoo(Foo foo) {
var newFoo = ...;
newFoo.Prop1 = foo.Prop1.Replace(....);
return newFoo;
}
If I need another view of Foo, I create yet another method.
Is there a more reuseable way of doing that?
I was thinking about having an attribute to those properties which define those views. Maybe something like this:
public class Foo {
[ViewMode(Mode="Name1", ViewClass=ViewClassWithOperations)
public string Prop1 { get; set; }
}
Where ViewClassWithOperations
are the operations applied to the properties. And with the Mode-Name I could decide which ViewClass I should instantiate and apply to Foo.
Does this even make sense? Is it too complicated? Do you have better ideas?
Take a look at C# Record Types (coming soon to C#). They include a With
method that behaves like this:
public Foo With(string prop1 = this.Prop1, string prop2 = this.prop2)
=> new Foo(prop1, prop2);
You can implement that today in C# and then call it passing named arguments for the properties you want to replace.
But when you say 'View' it sounds like you maybe should consider implementing a separate ViewModel class for Foo and maybe using Automapper to map properties across because sooner or later you will need a view like 'name' which is maybe constructed from 'first name + space + last name'. Reusing domain models as view models typically leads to problems down the line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.