繁体   English   中英

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

[英]How to check if property setter is public

给定一个 PropertyInfo 对象,如何检查该属性的 setter 是否是公共的?

检查您从GetSetMethod返回的GetSetMethod

MethodInfo setMethod = propInfo.GetSetMethod();

if (setMethod == null)
{
    // The setter doesn't exist or isn't public.
}

或者,换个角度看理查德的回答

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

请注意,如果您只想设置一个属性,只要它有一个 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 });
}

.NET 属性实际上是一个围绕 get 和 set 方法的包装外壳。

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

如果 getter/setter 是非公开的,这些方法将返回 null。

这里的正确代码是:

bool IsPublic = propertyInfo.GetSetMethod() != null;
public class Program
{
    class Foo
    {
        public string Bar { get; private set; }
    }

    static void Main(string[] args)
    {
        var prop = typeof(Foo).GetProperty("Bar");
        if (prop != null)
        {
            // The property exists
            var setter = prop.GetSetMethod(true);
            if (setter != null)
            {
                // There's a setter
                Console.WriteLine(setter.IsPublic);
            }
        }
    }
}

您需要使用底层方法来确定可访问性,使用PropertyInfo.GetGetMethod()PropertyInfo.GetSetMethod()

// Get a PropertyInfo instance...
var info = typeof(string).GetProperty ("Length");

// Then use the get method or the set method to determine accessibility
var isPublic = (info.GetGetMethod(true) ?? info.GetSetMethod(true)).IsPublic;

但是请注意,getter 和 setter 可能具有不同的可访问性,例如:

class Demo {
    public string Foo {/* public/* get; protected set; }
}

所以你不能假设 getter 和 setter 将具有相同的可见性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM