如何检查属性设置器是否公开

Ron*_*rby 57 .net c# reflection

给定PropertyInfo对象,如何检查属性的setter是否公开?

Dan*_*Tao 111

检查你得到的回复GetSetMethod:

MethodInfo setMethod = propInfo.GetSetMethod();

if (setMethod == null)
{
    // The setter doesn't exist or isn't public.
}
Run Code Online (Sandbox Code Playgroud)

或者,对理查德的回答采取不同的调整:

if (propInfo.CanWrite && propInfo.GetSetMethod(/*nonPublic*/ true).IsPublic)
{
    // The setter exists and is public.
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果你想要做的就是设置一个属性,只要它有一个setter,你实际上不必关心setter是否是公共的.您可以使用它,公共私人:

// This will give you the setter, whatever its accessibility,
// assuming it exists.
MethodInfo setter = propInfo.GetSetMethod(/*nonPublic*/ true);

if (setter != null)
{
    // Just be aware that you're kind of being sneaky here.
    setter.Invoke(target, new object[] { value });
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*fer 9

.NET属性实际上是围绕get和set方法的包装shell.

您可以GetSetMethod在PropertyInfo上使用该方法,返回引用setter的MethodInfo.你也可以做同样的事情GetGetMethod.

如果getter/setter是非公共的,则这些方法将返回null.

这里的正确代码是:

bool IsPublic = propertyInfo.GetSetMethod() != null;
Run Code Online (Sandbox Code Playgroud)