using System;
using System.Diagnostics;
using System.Reflection;
namespace ConsoleApp
{
class Program
{
private delegate ref int GetMaxNumber(ref int value1, ref int value2);
static void Main(string[] args)
{
int value1 = 5;
int value2 = 10;
var instance = new Something();
MethodInfo? methodInfo = typeof(Something).GetMethod(
nameof(Something.GetMax), BindingFlags.Public | BindingFlags.Instance);
Debug.Assert(methodInfo is not null);
var setNumber = (GetMaxNumber)Delegate.CreateDelegate(typeof(GetMaxNumber), instance, methodInfo);
setNumber.Invoke(ref value1, ref value2) = 50;
Console.WriteLine($"{nameof(value1)}: {value1}, {nameof(value2)}: {value2}");
}
}
public class Something
{
public ref int GetMax(ref int left, ref int right)
{
if (left > right)
{
return ref left;
}
return ref right;
}
}
}
Проверял на
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>