Doesn't C# Extension Methods allow passing parameters by reference?

前端 未结 3 1158
庸人自扰
庸人自扰 2020-12-03 17:19

Is it really impossible to create an extension method in C# where the instance is passed as a reference?

Here’s a sample VB.NET console app:

Imports          


        
3条回答
  •  甜味超标
    2020-12-03 17:27

    Yikes - you're making a mutable immutable struct. It breaks what people expect to see in C#, but if you must, then you can always directly call the method:

    Ext.Add(ref value, arg1);
    

    Any extension method is directly callable.

    Also, a clarification:

    SomeReferenceType value = ...;
    SomeReferenceType copy = value;
    value.ExtensionMethodByRef(...);
    // this failing is semantically ridiculous for reference types, which
    // is why it makes no sense to pass a `this` parameter by ref.
    object.ReferenceEquals(value, copy);
    

提交回复
热议问题