【发布时间】:2023-01-11 11:54:35
【问题描述】:
为什么禁止使用ref修饰符调用Extension Method?
这是可能的:
public static void Change(ref TestClass testClass, TestClass testClass2)
{
testClass = testClass2;
}
而这个不是:
public static void ChangeWithExtensionMethod(this ref TestClass testClass, TestClass testClass2)
{
testClass = testClass2;
}
但为什么?
【问题讨论】:
-
您确定需要显式
ref吗?我希望它是由this“自动生成”的——非引用扩展方法没有任何意义。 -
但如果我没记错的话,它们是非参考的。
-
@MarcelJackwerth ref 参数与引用类型参数不同。 ref 参数传递调用者的引用(或指针)本身。使用 ref 您可以更新引用以指向其他某个对象。没有它(对于引用类型),您可以更新对象本身,但不能更新对它的引用。
标签: c# .net extension-methods