C# 反射获取new操作符定义的属性
时间: 2023-11-28 15:50:54 浏览: 44
可以通过反射获取new操作符定义的属性,具体步骤如下:
1. 使用Type.GetMember方法获取指定类型的成员信息,设置BindingFlags参数为BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,这样就可以获取到该类型的所有成员,包括实例成员和静态成员,公共成员和非公共成员。
2. 遍历获取到的成员信息,判断成员是否为属性(PropertyInfo),并且该属性是否定义了new操作符。
3. 如果是,则可以通过MemberInfo.DeclaringType属性获取该属性所在的类型,即定义该属性的类型。
以下是一个示例代码:
```
using System;
using System.Reflection;
class BaseClass
{
public virtual int MyProperty { get; set; }
}
class DerivedClass : BaseClass
{
public new int MyProperty { get; set; }
}
class Program
{
static void Main(string[] args)
{
Type derivedType = typeof(DerivedClass);
MemberInfo[] members = derivedType.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
foreach (MemberInfo member in members)
{
if (member.MemberType == MemberTypes.Property)
{
PropertyInfo property = (PropertyInfo)member;
if (property.Name == "MyProperty" && property.DeclaringType == derivedType)
{
Console.WriteLine("Property {0} is defined in type {1}", property.Name, property.DeclaringType.Name);
}
}
}
}
}
```
运行该代码,输出结果为:
```
Property MyProperty is defined in type DerivedClass
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)