gpt4 book ai didi

c# - 如何查找 C# 类的内部属性?保护?保护内部?

转载 作者:可可西里 更新时间:2023-11-01 08:54:46 26 4
gpt4 key购买 nike

如果我有一个 C# 类 MyClass 如下:

using System.Diagnostics;

namespace ConsoleApplication1
{
class MyClass
{
public int pPublic {get;set;}
private int pPrivate {get;set;}
internal int pInternal {get;set;}
}
class Program
{
static void Main(string[] args)
{
Debug.Assert(typeof(MyClass).GetProperties(
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.Instance).Length == 1);
Debug.Assert(typeof(MyClass).GetProperties(
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance).Length == 2);
// internal?
// protected?
// protected internal?
}
}
}

上面编译的代码运行时没有任何断言失败。 NonPublic 返回 Internal 和 Private 属性。 BindingFlags 上似乎没有其他可访问性类型的标志。 .

如何获取仅包含内部属性的列表/数组?在相关说明中,但对于我的应用程序不是必需的, protected 或 protected 内部怎么样?

最佳答案

当您使用 BindingFlags.NonPublic 获取属性信息时, 您可以使用 GetGetMethod(true) 找到 getter 或 setter和 GetSetMethod(true) , 分别。然后,您可以检查(方法信息的)以下属性以获得确切的访问级别:

  • propertyInfo.GetGetMethod(true).IsPrivate表示私有(private)
  • propertyInfo.GetGetMethod(true).IsFamily表示 protected
  • propertyInfo.GetGetMethod(true).IsAssembly表示内部
  • propertyInfo.GetGetMethod(true).IsFamilyOrAssembly表示 protected 内部
  • propertyInfo.GetGetMethod(true).IsFamilyAndAssembly表示私有(private)保护

对于 GetSetMethod(true) 同样如此当然。

请记住,让其中一个访问器(getter 或 setter)比另一个访问器更受限制是合法的。如果只有一个访问器,那么它的可访问性就是整个属性的可访问性。如果两个访问器都存在,可访问的访问器将为您提供整个属性的可访问性。

使用 propertyInfo.CanRead看看是否可以调用propertyInfo.GetGetMethod ,并使用 propertyInfo.CanWrite看看是否可以调用propertyInfo.GetSetMethod . GetGetMethodGetSetMethod方法返回 null如果访问器不存在(或者如果它是非公共(public)的而您要求公共(public)访问器)。

关于c# - 如何查找 C# 类的内部属性?保护?保护内部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16024006/

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