mercredi 13 septembre 2017

How to get name of a property passed by linq expression?

I am trying to avoid misspelling by passing property names as linq expressions like

AnyFunction(t => t.prop);

However, it seems like I cannot retrieve the name prop inside a function called like this.

Can I do that? Here is what I have tried.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace My.LanguageTests
{
  [TestClass]
  public class ReflectionTest
  {
    [TestMethod]
    public void TestMethod1()
    {
      var name = GetName((TheClass t) => t.prop);
      Assert.AreEqual("prop", name);
    }

    private string GetName<T>(Func<T, int> input)
    {
      return input.Method.Name;
    }

    public class TheClass
    {
      public int prop { get; set; }
    }
  }
}

This test fails with the result

Message:    Assert.AreEqual failed.
Expected:<prop>. Actual:<<TestMethod1>b__0_0>.





Aucun commentaire:

Enregistrer un commentaire