gpt4 book ai didi

c# - 如何避免在变量赋值的上下文中调用冗余?

转载 作者:行者123 更新时间:2023-11-30 20:57:29 25 4
gpt4 key购买 nike

我经常(就像现在一样)像这样编写 C#(或 vb.net)代码:

someObject.field_1 = doSomething( 
anotherObject_1.propertyA,
anotherObject_1.propertyB);

someObject.field_2 = doSomething(
anotherObject_2.propertyA,
anotherObject_2.propertyB);

// some more field in same schema.

someObject.field_X = doSomething(
anotherObject_X.propertyA,
anotherObject_X.propertyB);

编辑 anotherObject_1 .. anotherObject_X 具有相同的类型; someObject 和 anotherObject 的类型通常不同。

问题是可扩展性和可维护性。新领域让我可以编写几乎相同的代码,只是对象命名上的差异很小。

通过将逻辑封装在 doSomething(..) 中,我避免了逻辑冗余,但是调用冗余仍然很烦人。

有没有办法(例如模式或 .Net (4.0) 语言结构)来避免这种情况?

最佳答案

您可以将集合操作封装到不同的方法中

void SetField(ref int field, object anotherObjectX)
{
field = doSmth(anotherObjectX...);
}

SetField(ref object.field1, anotherObject1);
SetField(ref object.field2, anotherObject2);
SetField(ref object.field3, anotherObject3);

但您仍然需要为每个新字段添加新行

关于c# - 如何避免在变量赋值的上下文中调用冗余?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16806015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com