2

因此,PropertyInfo 有一个 GetSetMethod 方法,该方法返回此属性的 setter 方法。它还有一个相同的 SetMethod 属性(据我所知)。

我问这个是因为如果属性不是公共的,而 SetMethod 仍然有效,GetSetMethod 似乎返回 null 。

我在 MSDN 上找不到太多。

4

3 回答 3

4

你是对的。

那来自 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);
      }
    }
于 2013-10-30T18:34:50.093 回答
4

他们做同样的事情,但属性是新添加的:已添加到 .NET 4.5 中,而GetSetMethod.NET 2.0 以来一直存在。

唯一的区别是该属性将返回 setter,即使它是非公共的,而该方法将只返回public一个。从文档中:

返回此属性的公共集访问器。[方法文档]

对比

获取此属性的 set 访问器。[财产文件]

于 2013-10-30T18:34:53.450 回答
3

SetMethod只是一个快捷方式GetSetMethod(true)(即,无论它是否公开,它都会返回 setter 方法)。它是这样实现的:

public virtual MethodInfo SetMethod
{   
    get
    {
        return this.GetSetMethod(true);
    }
}
于 2013-10-30T18:35:09.647 回答