Hun*_*hpu 28 .net c# extension-methods
为什么禁止Extension Method用ref修饰符调用?
这个是可能的:
public static void Change(ref TestClass testClass, TestClass testClass2)
{
testClass = testClass2;
}
Run Code Online (Sandbox Code Playgroud)
这不是:
public static void ChangeWithExtensionMethod(this ref TestClass testClass, TestClass testClass2)
{
testClass = testClass2;
}
Run Code Online (Sandbox Code Playgroud)
但为什么?
Jon*_*eet 21
你必须指定ref和out明确.你会怎么用扩展方法做到这一点?而且,你真的想要吗?
TestClass x = new TestClass();
(ref x).ChangeWithExtensionMethod(otherTestClass);
// And now x has changed?
Run Code Online (Sandbox Code Playgroud)
或者您是否希望不必指定ref部件,仅用于扩展方法中的第一个参数?
对我来说,这听起来很奇怪,说实话,以及不可读(或至少难以预测)代码的配方.
jul*_*uck 12
在 C# 7.2 中,您可以对结构使用 ref 扩展方法
请参阅https://github.com/dotnet/csharplang/issues/186和https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.2/readonly-ref.md
drw*_*ode 11
我同意Jon Skeet等人的答案.关于如何允许"ref this"扩展方法可以使代码更加模糊.但是,如果您查看.Net Framework中的某些命名空间,则在结构上调用的方法通常会对其进行更改.
以System.Drawing结构(Point,Rectangle等)为例.其中每一个都有改变结构本身的方法(例如Offset,Inflate等).我不是说这是一个好主意,事实上我个人觉得Offset,Inflate等变异结构本身而不是返回新结构非常烦人,我知道你们中的一些人反对改变结构的想法一般.
我怀疑在任何情况下调用引用类型的方法都会改变引用(除非它与String类有关,我可以想象可能有一些编译器魔术来切换引用以执行实习等).因此,防止"this ref"与引用类型一起使用是有意义的,因为更改引用将是调用方法的完全非标准的副作用.
但是就结构而言,允许"this ref"不会显着降低代码可读性而不仅仅是Rectangle.Inflate等,它将提供用扩展函数"模拟"这种行为的唯一方法.
正如旁注,这里有一个例子,其中"这个参考" 可能是有用的,恕我直言仍然可读:
void SwapWith<T>(this ref T x, ref T y) {
T tmp = x; x = y; y = tmp;
}
Run Code Online (Sandbox Code Playgroud)
小智 9
我知道这是一个老问题。但事情已经发生了变化。如果有人正在寻找这个。
从 C# 7.2 开始,您可以将 ref 修饰符添加到扩展方法的第一个参数。添加 ref 修饰符意味着第一个参数通过引用传递。这使您能够编写更改被扩展结构状态的扩展方法。
这仅适用于值类型 ( struct),而不适用于引用类型 ( class, interface, record)。
来源:Microsoft Docs,“扩展方法(C# 编程指南)——扩展预定义类型”。
public struct MyProperties
{
public string MyValue { get; set; }
}
public static class MyExtensions
{
public static void ChangeMyValue(this ref MyProperties myProperties)
{
myProperties.MyValue = "hello from MyExtensions";
}
}
public class MyClass
{
public MyClass()
{
MyProperties myProperties = new MyProperties();
myProperties.MyValue = "hello world";
myProperties.ChangeMyValue();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9695 次 |
| 最近记录: |