【发布时间】:2015-11-24 20:14:22
【问题描述】:
我正在为一些自定义的小容量编码和解码算法编写值类型的扩展方法(例如int)。
可能还有其他设计不使用扩展方法,但我担心这不是我最后一次遇到这个问题,所以我想知道扩展方法如何与这种类型一起工作设计。
例如:
int i = 10;
string str = i.Encode(); // Convert 10 to an unpredictable string such as "tZh0Ao"
i = 5; // Overwrite i with a new value.
i.Decode(str); // Decrypt the string to reassign the original value of 10
我不确定 this 参数如何用于值类型扩展方法。
它只是原始值的副本吗?
或者它是否像 ref 或 out 参数一样工作,保留对参数值所做的更改?
例如:
/* This method will decode a string,
and assign the decoded value to 'this' int. */
public static void Decode(this int value, string str)
{
int result;
/* ... perform work with str to produce decoded value ... */
value = result; // Assign the decoded value to 'this' int.
/* If 'value' is just a copy of the original int,
the assignment won't have any permanent effect. */
}
【问题讨论】:
-
它不是
ref传递的,所以它不会更新你调用它的原始变量。 -
最好让它返回
int。public static int Decode(string str)。所以不是i.Decode(str);,而是i = Decode(str); -
在 MSDN 论坛上也有一个有趣的讨论; Extension methods can't use 'ref' and 'this' at the same time?
-
还阅读了 C# 中的扩展方法,这很容易阅读 - codeproject.com/Tips/709310/Extension-Method-In-Csharp
标签: c# .net pass-by-reference extension-methods value-type