C# 从方法参数获取原始属性名称

C# 从方法参数获取原始属性名称,c#,methods,reflection,parameters,C#,Methods,Reflection,Parameters,如何获取作为参数传递给方法的原始属性名的名称 class TestA { public string Foo { get; set; } public TestA() { Foo = "Bar"; TestB.RegisterString(Foo); } } class TestB { public static void Regi

如何获取作为参数传递给方法的原始属性名的名称

class TestA
    {
        public string Foo { get; set; }

        public TestA()
        {
            Foo = "Bar";

            TestB.RegisterString(Foo);
        }
    }

    class TestB
    {
        public static void RegisterString(string inputString)
        {
            // Here I want to receive the property name that was used
            // to assign the parameter input string
            // I want to get the property name "Foo"
        }
    }

您可以添加带有
nameof
关键字的参数。我不知道你为什么要这样做:

TestB.RegisterString(Foo, nameof(Foo));
这将作为第二个参数传入
“Foo”
。没有办法自动执行此操作,因此您不需要自己调用
nameof
,这使得执行此操作毫无用处

如果要从
Foo
属性调用此函数,可以使用
CallerMemberNameAttribute
,它将输入调用方的名称。编译器将设置正确的值,因此您不必在调用方法中自己提供该值

public static void RegisterString( string inputString
                                 , [CallerMemberName] string caller = null
                                 )
{
    // use caller here
}

这对我来说更有意义。

不可能。为什么需要它?我想为同名命令实现一些自动注册:/谢谢你的评论。属性将是更干净的解决方案?是的,但您需要将该代码放入
Foo
。不确定这是否是你想要的,但从我的观点来看,它更好。值得一提的是-关键字在VS 2015中是新的(C#6)