在 C# 中使用 nameof 获取 setter 方法名称
Using nameof to get a setter method name in c#
是否可以使用新的 nameof
运算符获得 setter 方法名称?
public object Foo { get; set; }
public void Test()
{
var myMethod = GetType().GetMethod("set_Foo");
}
我想 GetType().GetMethod("set_" + nameof(Foo))
可以工作,但有没有更直接的方法?
类似 -
var type = typeof(Test).GetProperties().FirstOrDefault().GetAccessors(false);
其中 Test
是具有 property
S3
类型 string
的 type
。
不能直接使用nameof
获取setter方法名。
你可以结合反射得到属性,用PropertyInfo.SetMethod
得到setter:
MethodInfo setterMethod = GetType().GetProperty(nameof(Foo)).SetMethod;
string setterName = setterMethod.Name;
是否可以使用新的 nameof
运算符获得 setter 方法名称?
public object Foo { get; set; }
public void Test()
{
var myMethod = GetType().GetMethod("set_Foo");
}
我想 GetType().GetMethod("set_" + nameof(Foo))
可以工作,但有没有更直接的方法?
类似 -
var type = typeof(Test).GetProperties().FirstOrDefault().GetAccessors(false);
其中 Test
是具有 property
S3
类型 string
的 type
。
不能直接使用nameof
获取setter方法名。
你可以结合反射得到属性,用PropertyInfo.SetMethod
得到setter:
MethodInfo setterMethod = GetType().GetProperty(nameof(Foo)).SetMethod;
string setterName = setterMethod.Name;