程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了GetProperties()返回接口继承层次结构的所有属性大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决GetProperties()返回接口继承层次结构的所有属性?

开发过程中遇到GetProperties()返回接口继承层次结构的所有属性的问题如何解决?下面主要结合日常开发的经验,给出你关于GetProperties()返回接口继承层次结构的所有属性的解决方法建议,希望对你解决GetProperties()返回接口继承层次结构的所有属性有所启发或帮助;

我已经将@marc Gravel的示例代码调整为一个有用的扩展方法,该方法封装了类和接口。我还首先添加了接口属性,我认为这是预期的行为。

public static PropertyInfo[] GetPublicPropertIEs(this Type typE)
{
    if (type.IsInterfacE)
    {
        var propertyInfos = new List<PropertyInfo>();

        var consIDered = new List<Type>();
        var queue = new Queue<Type>();
        consIDered.Add(typE);
        queue.Enqueue(typE);
        while (queue.Count > 0)
        {
            var subType = queue.Dequeue();
            foreach (var subInterface in subType.GeTinterfaces())
            {
                if (consIDered.Contains(subInterfacE)) conTinue;

                consIDered.Add(subInterfacE);
                queue.Enqueue(subInterfacE);
            }

            var typePropertIEs = subType.GetPropertIEs(
                BindingFlags.FlattenHIErarchy 
                | BindingFlags.Public 
                | BindingFlags.InstancE);

            var newPropertyInfos = typePropertIEs
                .Where(x => !propertyInfos.Contains(X));

            propertyInfos.InsertRange(0, newPropertyInfos);
        }

        return propertyInfos.ToArray();
    }

    return type.GetPropertIEs(BindingFlags.FlattenHIErarchy
        | BindingFlags.Public | BindingFlags.InstancE);
}
@H_262_6@

解决方法

假设以下假设继承层次结构:

public interface IA
{
  int id { get; set; }
}

public interface IB : IA
{
  String Name { get; set; }
}
@H_262_6@

使用反射并进行以下调用:

typeof(IB).GetProperties(BindingFlags.Public | BindingFlags.InstancE)
@H_262_6@

只会产生interface的属性IB@H_262_6@,即“ Name@H_262_6@”。

如果我们要对以下代码进行类似的测试,

public abstract class A
{
  public int id { get; set; }
}

public class B : A
{
  public String Name { get; set; }
}
@H_262_6@

该调用typeof(B).GetProperties(BindingFlags.Public | BindingFlags.InstancE)@H_262_6@将返回PropertyInfo@H_262_6@“ ID@H_262_6@”和“ Name@H_262_6@” 的对象数组。

是否像第一个示例一样,有一种简单的方法可以在接口的继承层次结构中找到所有属性?

大佬总结

以上是大佬教程为你收集整理的GetProperties()返回接口继承层次结构的所有属性全部内容,希望文章能够帮你解决GetProperties()返回接口继承层次结构的所有属性所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。