[英]How to change an object property passed as a parameter?
I want to pass an object to a method, however during this I want to change a property of said object. 我想将对象传递给方法,但是在此期间,我想更改所述对象的属性。 The way I do it now is like this: 我现在的方式是这样的:
MyClass someClass= someClasses.FirstOrDefault(s => s.Propert1. == "1");
someClass.Property1 = 2;
MyMethod(someClass);
However I dont want to do the extra step of creating a variable and then setting the property. 但是,我不想执行创建变量然后设置属性的额外步骤。
MyMethod(someClasses.FirstOrDefault(s => s.Propert1. == "1")/*.ChangeProperty()?*/); //This is where I would like to change Property1's value.
Is this good practice, if at all possible? 如果可能的话,这是一种好的做法吗?
I don't see any reason to do this on a single line. 我看不出有任何理由在一行上执行此操作。 This code looks absolutely fine: 这段代码看起来绝对不错:
MyClass someClass= someClasses.FirstOrDefault(s => s.Propert1. == "1");
someClass.Property1 = 2;
MyMethod(someClass);
If you want, you could add an extension method that does this: 如果需要,可以添加一个扩展方法来执行以下操作:
// put this in a static class
static T WithNewPropertyValue<T>(this T t, Action<T> action) where T : class
{
action(t);
return t;
}
And call it like this 并这样称呼它
MyMethod(someClasses.FirstOrDefault(s => s.Propert1 == "1").WithNewPropertyValue(x => x.Propert1 = "2"));
But I feel like this decreases the readability of the code. 但是我觉得这样会降低代码的可读性。
You can do it with the extension method which changes a property and returns changed object : 您可以使用扩展方法来执行此操作,该方法可以更改属性并返回更改的对象 :
public static MyClass WithProperty2(this MyClass source, int value)
{
if (source != null) // make sure you handle null
source.Property2 = value;
return source;
}
Now you have a fluent API to do one-liners (which does not make your code much more maintainable): 现在,您可以使用流畅的API来执行一线工作(这不会使您的代码更易于维护):
MyMethod(someClasses.FirstOrDefault(s => s.Propert1. == "1").WithProperty2(42))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.