给定一个PropertyInfo对象,如何判断该属性的setter是否为public?

推荐答案

判断你从GetSetMethod中得到了什么:

MethodInfo setMethod = propInfo.GetSetMethod();

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

或者,对Richard's answer进行不同的旋转:

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

请注意,如果您只想设置一个属性,只要它有setter,那么您实际上不必关心setter是否是公共的.你可以直接用它,公共的or个私有的:

// 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相关问答推荐

Docker镜像mcr.microsoft.com/dotnet/aspnet:8.0不能在Windows上构建

如何在 C# 中自动删除临时文件?

在 .NET 反射中使用 GetProperties() 和 BindingFlags.DeclaredOnly

.NET 的 Visual Studio 调试器提示和技巧

为什么 C# 不允许像 C++ 这样的非成员函数

指定的版本字符串不符合要求的格式 - major[.minor[.build[.revision]]]

SubscribeOn 和 ObserveOn 有什么区别

控制台应用程序的退出时

无法加载文件或程序集'System.ComponentModel.Annotations,版本 = 4.1.0.0

Convert.ToBoolean 和 Boolean.Parse 不接受 0 和 1

C#As的 VB.NET 类似功能

如何对 LINQ to XML 中的元素进行深层复制?

如何防止任务的同步延续?

在任务中捕获异常的最佳方法是什么?

接口属性的 XML 序列化

通过反射查找可空属性的类型

为什么甚至可以更改私有成员,或使用反射在 C# 中运行私有方法?

如何重新启动 WPF 应用程序?

.NET 中的 java.lang.IllegalStateException?

序列化一个可为空的 int