gpt4 book ai didi

c# - 如何检查属性 setter 是否公开

转载 作者:IT王子 更新时间:2023-10-29 03:47:15 25 4
gpt4 key购买 nike

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

最佳答案

检查您从 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 是否是公共(public)的。您可以直接使用它,公共(public)私有(private):

// 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 });
}

关于c# - 如何检查属性 setter 是否公开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3762456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com