简体   繁体   English

使用nameof在c#中获取setter方法名称

[英]Using nameof to get a setter method name in c#

Is it possible to get a setter method name using the new nameof operator? 是否可以使用新的nameof运算符获取setter方法名称?

public object Foo { get; set; }

public void Test()
{        
    var myMethod = GetType().GetMethod("set_Foo");       
}

I guess GetType().GetMethod("set_" + nameof(Foo)) could work but is there something more straightforward? 我猜GetType().GetMethod("set_" + nameof(Foo))可以工作,但还有更直接的东西吗?

You can't use nameof to get the setter method name directly. 您不能使用nameof直接获取setter方法名称。

You can combine it with reflection to get the property and use PropertyInfo.SetMethod to get the setter: 您可以将它与反射结合以获取属性并使用PropertyInfo.SetMethod来获取setter:

MethodInfo setterMethod = GetType().GetProperty(nameof(Foo)).SetMethod;
string setterName = setterMethod.Name;

Something like - 就像是 -

var type = typeof(Test).GetProperties().FirstOrDefault().GetAccessors(false);

where Test is the type with a property S3 of type string . 其中Test是具有typestringproperty S3的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM