Как в C# (.NET) задать значение возвращаемого методом значения через ref, используя reflection?

Есть примерно такой код:
private ref int GetRefValue(int code)
        {
            //blah blah
            return ref something;
        }

По-нормальному вызывается он так:
this.GetRefValue(code) = value;
А как это вызвать через reflection?
  • Вопрос задан
  • 166 просмотров
Решения вопроса 1
Casper-SC
@Casper-SC
Программист (.NET)
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>
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы