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)
.NET属性实际上是围绕get和set方法的包装shell.
您可以GetSetMethod
在PropertyInfo上使用该方法,返回引用setter的MethodInfo.你也可以做同样的事情GetGetMethod
.
如果getter/setter是非公共的,则这些方法将返回null.
这里的正确代码是:
bool IsPublic = propertyInfo.GetSetMethod() != null;
Run Code Online (Sandbox Code Playgroud)