您的位置:首页 > 其它

反射的结果中排除隐藏的成员

2016-03-09 19:33 369 查看
问题:实例化的对象,反射后得到的列表包含了被隐藏的基类成员,这时如果转换为hashtable将会报key以存在的错误,如果单独使用GetProperty(“”),将会引发异常“System.Reflection.AmbiguousMatchException”

分析:找不到办法得到不包含基类成员集合,因为他们声明在不同的类中。

解决方法:DeclaringType得到“获取声明该成员的类”, ReflectedType得到“获取用于获取 MemberInfo 的此实例的类对象”,通过对这两个的判断找到被隐藏的基类成员,并从集合中排除。

源码:

using Fasterflect;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
class3 cls = new class3();
cls.id = "guid";
cls.value = "1.25F";

var propertyArray = cls.GetType().GetProperties().ToList();

foreach (var item in propertyArray)
{
Console.WriteLine(item.PropertyType.ToString() + ":" + item.Name);
}

// 排除基类被隐藏的成员
var tmpList = from a in propertyArray
group a by a.Name into g
select g;
foreach (var item in tmpList)
{
if (item.Count() > 1)
{
var itemSubList = item.Where(a => a.DeclaringType != a.ReflectedType);
foreach (var sub in itemSubList)
{
propertyArray.Remove(sub);
}
}
}

Console.WriteLine();
Console.WriteLine("——————————————");
Console.WriteLine("排除基类中的被隐藏的成员:");
foreach (var item in propertyArray) {
Console.WriteLine(item.PropertyType.ToString() + ":" + item.Name);
}

Console.Read();
}
}

class class1
{
private string pri { get; set; }
public object value { get; set; }
public virtual string id { get; set; }
}

class class2 : class1
{
new public float value { get; set; }

public string test { get; set; }

public override string id { get; set; }
}

class class3 : class2
{
new public string value { get; set; }
}
}


参考:

https://msdn.microsoft.com/zh-cn/library/435f1dw2.aspx

http://blogs.msdn.com/b/weitao/archive/2007/04/26/binding-to-hidden-properties-using-reflection.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: