C# 如何根据指定实体类和字段名称查找字段

gzg555888 2010-10-15 08:55:42
目的是把

三层架构 里的model层 作为实体对象 以及 已知的字段名称 传入方法中,然后调用字段名称来获取字段对应的值。




Package1.Model.I_C_PC IcPcl = new Package1.Model.I_C_PC();

string str = ziduanming;




这个方法应该如何写?麻烦各位大侠指导一下.
...全文
837 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
gzg555888 2010-10-17
  • 打赏
  • 举报
回复
没人吗
I520WUCHAN 2010-10-16
  • 打赏
  • 举报
回复
顶............
I520WUCHAN 2010-10-16
  • 打赏
  • 举报
回复
顶............
gzg555888 2010-10-16
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wuyq11 的回复:]
Type t = Test.GetType().GetProperty("Property1").GetValue(b, null).GetType();
foreach (PropertyInfo info in TEST.GetType().GetProperty("Property1").GetValue(TEST, null).GetType().GetProperties())
……

尝试过了。我对反射这个方法不熟。能有谁讲解下吗
[/Quote]


老师带小朋友到山上玩,小明看到一条牛没有犄角,就问老师:“老师,老师,为什么这条牛没有犄角啊?”
小强抢着回答:“因为它得病了”。
老师说:“不对”。
小伟说:“因为它跟别的牛格斗,把犄角斗没了”。
老师说:“也不对”。
“那是为什么呢?”小强问。
“因为它是一头驴..”老师说。

汗........
狂汗......
gzg555888 2010-10-15
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wuyq11 的回复:]
Type t = Test.GetType().GetProperty("Property1").GetValue(b, null).GetType();
foreach (PropertyInfo info in TEST.GetType().GetProperty("Property1").GetValue(TEST, null).GetType().GetProperties())
……
[/Quote]
能详细 解释下吗
skyering 2010-10-15
  • 打赏
  • 举报
回复
其实就是C#中的反射。可以看一下反射相关内容。
gzg555888 2010-10-15
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wuyq11 的回复:]
Type t = Test.GetType().GetProperty("Property1").GetValue(b, null).GetType();
foreach (PropertyInfo info in TEST.GetType().GetProperty("Property1").GetValue(TEST, null).GetType().GetProperties())
……
[/Quote]
想 请问下这里 Test 是指 我的model吗? GetValue(b, null) 这里的b是字段名是吗? 那
gzg555888 2010-10-15
  • 打赏
  • 举报
回复
查看了其他 帖子说是可以通过反射进行查找

public static object FindField(object container, string fieldName)
{
object obj = null;

System.Reflection.BindingFlags bindingFlags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static;
System.Reflection.FieldInfo field = container.GetType().GetField(fieldName, bindingFlags);
if (field != null)
{
obj = field.GetValue(container);
}


return obj;
}


但是我传model进这个方法后 这段代码不知道应该如何修改field都是null值
wuyq11 2010-10-15
  • 打赏
  • 举报
回复
Type t = Test.GetType().GetProperty("Property1").GetValue(b, null).GetType();
foreach (PropertyInfo info in TEST.GetType().GetProperty("Property1").GetValue(TEST, null).GetType().GetProperties())
{
MessageBox.Show(string.Format("{0}={1}",info.Name,info.GetValue(TEST.Property1,null)));
}

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧