[英]Extension methods, which is a better choice
Following is a test class以下是测试类
public class Test
{
public int a;
}
Following are the Extension methods I have created:以下是我创建的扩展方法:
public static class Extension
{
public static void Do1(this Test t,int value)
{
t.a = t.a + value;
}
public static Test Do2(this Test t,int value)
{
t.a = t.a + value;
return t
}
}
Code Usage:代码用法:
Test t = new Test();
t.a = 5;
Both the following calls lead to same result for ta, which is 10
:以下两个调用都会导致ta, which is 10
相同结果ta, which is 10
:
t.Do1(5)
t = t.Do2(5)
There are many instances in my code where I need to implement a similar logic, which one is better, one of them is passing reference by value and internally updating it, other is returning the updated reference.我的代码中有很多实例需要实现类似的逻辑,哪个更好,其中一个是按值传递引用并在内部更新它,另一个是返回更新后的引用。 Is using one of them safer, if this kind of code ever gets into multi threaded wrapper, provided all the thread safety is taken care of.如果这种代码进入多线程包装器,那么使用其中一个是否更安全,前提是所有线程安全都得到了照顾。 Normally to update the referenced variable we need a ref or out keyword, which is like pointer to a pointer, instead of a separate pointer to same memory location as in this case, but here in extension methods, I cannot use them.通常要更新引用的变量,我们需要一个 ref 或 out 关键字,它类似于指向指针的指针,而不是像这种情况下指向同一内存位置的单独指针,但在扩展方法中,我不能使用它们。 Please let me know if the question needs further clarity如果问题需要进一步澄清,请告诉我
In your example it does not make sense to return the t
variable.在您的示例中,返回t
变量没有意义。 t
is a reference, so setting ta
updates the object already. t
是一个引用,所以设置ta
已经更新了对象。 There's no need for ref
, out
or returning t
.不需要ref
、 out
或返回t
。 One reason for returning t
would be to allow you to use method chaining.返回t
原因之一是允许您使用方法链。
You only need ref
or out
if you want to actually change the reference, not the content of the reference.如果要实际更改引用,而不是引用的内容,则只需要ref
或out
。
You are actually misunderstanding sense of ref
and out
keywords.您实际上误解了ref
和out
关键字的含义。 Those are used, if you want to replace whole referenced object inside your method, for simple property level update they are not needed at all.如果您想替换方法内的整个引用对象,则使用它们,对于简单的属性级别更新,根本不需要它们。
In your example, as Test
is a class (reference type), there is no actual difference between two methods, but returning initial Test
object as in Do2
method is just pointless, as object was already updated.在您的示例中,由于Test
是一个类(引用类型),因此两种方法之间没有实际区别,但是在Do2
方法中返回初始Test
对象毫无意义,因为对象已经更新。 So best of two will be the first implementation:所以最好的两个将是第一个实现:
public static class Extension
{
public static void Do1(this Test t,int value)
{
t.a = t.a + value;
}
}
Going back to Do2 method - as I said before, referenced object value is already updated inside a method, so there is even no point in assigning return value to initial variable:回到 Do2 方法 - 正如我之前所说,引用的对象值已经在方法内部更新,因此将返回值分配给初始变量甚至没有意义:
t.Do2(5)
is the same as是相同的
t.Do(5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.