C# 如何检查属性设置器是否是公共的
给定一个PropertyInfo对象,如何检查该属性的setter是否为public?.NET属性实际上是一个围绕get和set方法的包装外壳 您可以在PropertyInfo上使用C# 如何检查属性设置器是否是公共的,c#,.net,reflection,C#,.net,Reflection,给定一个PropertyInfo对象,如何检查该属性的setter是否为public?.NET属性实际上是一个围绕get和set方法的包装外壳 您可以在PropertyInfo上使用GetSetMethod方法,返回引用setter的MethodInfo。您可以使用getmethod执行相同的操作 如果getter/setter是非公共的,这些方法将返回null 这里的正确代码是: bool IsPublic = propertyInfo.GetSetMethod() != null; 检查您
GetSetMethod
方法,返回引用setter的MethodInfo。您可以使用getmethod
执行相同的操作
如果getter/setter是非公共的,这些方法将返回null
这里的正确代码是:
bool IsPublic = propertyInfo.GetSetMethod() != null;
检查您从以下方面获得的回报: 或者,换一种说法: 注意,如果您只想设置一个属性,只要它有一个setter,那么实际上您不必关心setter是否是公共的。您可以使用它,公共或私人:
您需要使用下划线方法来确定可访问性,使用或 但是,请注意,getter和setter可能具有不同的可访问性,例如:
class Demo {
public string Foo {/* public/* get; protected set; }
}
因此,您不能假设getter和setter具有相同的可见性。+1:这比
GetSetMethod()。IsPublic
:当属性没有setter时,它也可以工作。请查看IsAssembly()
,以便检查它是否为内部设置代码>
if (propInfo.CanWrite && propInfo.GetSetMethod(/*nonPublic*/ true).IsPublic)
{
// The setter exists and is public.
}
// 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 });
}
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);
}
}
}
}
// 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;
class Demo {
public string Foo {/* public/* get; protected set; }
}