从方法参数中获取原始 属性 名称
Get the original property name from a method parameter
如何获取作为参数传递给方法的原始 属性 名称?
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
}
这对我来说更有意义。
如何获取作为参数传递给方法的原始 属性 名称?
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
}
这对我来说更有意义。