简体   繁体   English

应用了不同操作集的C#类

[英]C# Class having different set of operations applied to

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. 现在我想拥有Foo的副本,同时对某些属性应用一些操作。

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. 如果我需要Foo的另一个视图,我创建了另一种方法。

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. ViewClassWithOperations是应用于属性的操作。 And with the Mode-Name I could decide which ViewClass I should instantiate and apply to Foo. 使用Mode-Name,我可以决定我应该实例化哪个ViewClass并应用于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#). 看一下C#记录类型 (即将推出C#)。 They include a With method that behaves like this: 它们包含一个With方法,其行为如下:

 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. 您现在可以在C#中实现它,然后调用它为要替换的属性传递命名参数。

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'. 但是当你说“查看”时,你可能应该考虑为Foo实现一个单独的ViewModel类,并且可能使用Automapper来映射属性,因为迟早你需要一个像'name'这样的视图,它可能是用'名字'构造的+空格+姓氏'。 Reusing domain models as view models typically leads to problems down the line. 将域模型重用为视图模型通常会导致问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM