GetSetMethod 和 SetMethod 在 PropertyInformation 上有什么区别
本文关键字:什么 区别 PropertyInformation SetMethod GetSetMethod | 更新日期: 2023-09-27 18:37:27
因此,PropertyInfo 有一个返回此属性的 setter 方法的 GetSetMethod 方法。它还有一个 SetMethod 属性可以执行相同的操作(据我所知)。
我之所以问这个问题,是因为如果属性不是公共的,而 SetMethod 仍然有效,则 GetSetMethod 似乎返回 null。
我在MSDN上找不到太多。
它们执行相同的操作,但属性是新添加的:已在 .NET 4.5 中添加,而 GetSetMethod
自 .NET 2.0 以来一直存在。
唯一的区别是,即使属性是非公共的,该属性也会返回 setter,而该方法将只返回一个public
的 setter。从文档中:
返回此属性的公共集访问器。[方法文档]
与。
获取此属性的 set 访问器。[属性文件]
你是对的。
这是来自mscorlib(刚刚使用的dotPeek):
/// <summary>
/// Returns the public set accessor for this property.
/// </summary>
///
/// <returns>
/// The MethodInfo object representing the Set method for this property if the set accessor is public, or null if the set accessor is not public.
/// </returns>
[__DynamicallyInvokable]
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public MethodInfo GetSetMethod()
{
return this.GetSetMethod(false);
}
/// <summary>
/// When overridden in a derived class, returns the set accessor for this property.
/// </summary>
///
/// <returns>
/// Value Condition A <see cref="T:System.Reflection.MethodInfo"/> object representing the Set method for this property. The set accessor is public.-or- <paramref name="nonPublic"/> is true and the set accessor is non-public. null<paramref name="nonPublic"/> is true, but the property is read-only.-or- <paramref name="nonPublic"/> is false and the set accessor is non-public.-or- There is no set accessor.
/// </returns>
/// <param name="nonPublic">Indicates whether the accessor should be returned if it is non-public. true if a non-public accessor is to be returned; otherwise, false. </param><exception cref="T:System.Security.SecurityException">The requested method is non-public and the caller does not have <see cref="T:System.Security.Permissions.ReflectionPermission"/> to reflect on this non-public method. </exception>
[__DynamicallyInvokable]
public abstract MethodInfo GetSetMethod(bool nonPublic);
[__DynamicallyInvokable]
public virtual MethodInfo SetMethod
{
[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this.GetSetMethod(true);
}
}
SetMethod
只是GetSetMethod(true)
的快捷方式(即无论它是否公开,它都返回setter方法)。它是这样实现的:
public virtual MethodInfo SetMethod
{
get
{
return this.GetSetMethod(true);
}
}