因此,PropertyInfo有一个GetSetMethod方法,该方法返回此属性的setter方法。它还有一个相同的SetMethod属性(据我所知)。
我问这个是因为看起来GetSetMethod如果属性不公开则返回null,而SetMethod仍然有效。
我在MSDN上找不到多少。
答案 0 :(得分:4)
他们做同样的事情,但属性是新增加的:已经在.NET 4.5中添加了,而GetSetMethod
自.NET 2.0以来一直存在。
唯一的区别是属性将返回setter,即使它是非公共的,而该方法只返回public
个。来自文档:
返回此属性的 public set访问器。 [Method documentation]
VS
获取此属性的set访问器。 [Property documentation]
答案 1 :(得分:3)
你是对的。
那是来自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);
}
}
答案 2 :(得分:3)
SetMethod
只是GetSetMethod(true)
的快捷方式(即无论是否公开,它都会返回setter方法)。它以这种方式实现:
public virtual MethodInfo SetMethod
{
get
{
return this.GetSetMethod(true);
}
}