日期:2014-05-20  浏览次数:20736 次

以前的问题,没有好的方法解决。再发出来请高手看看。
先说说要求啊。
1.类aa,bb没基类。他们都默认继承Object。
2.实现不能只局限为aa,bb。可以适用有name属性的所有类,比如再加个cc,dd,ee方法不改同样适用。

谢谢高手帮忙解决啊。。有点难度~~

using   System;
using   System.Collections.Generic;
using   System.Text;

namespace   ConsoleApplication1
{
        class   Program
        {
                static   void   Main(string[]   args)
                {
                        aa   a   =   new   aa();
                        a.name   =   "aaa ";

                        bb   b   =   new   bb();
                        b.name   =   "bbb ";

                        cc(传个类进来);//输出类的Name属性
                        Console.Read();
                }
                public   static     void   cc(Object   obj)
                {
                        //该怎么写
                }
        }
        class   aa
        {
                public   string   name;
        }

        class   bb
        {
                public   string   name;
        }
}


------解决方案--------------------
public static void cc(Object obj)
{
Type type = obj.GetType();
FieldInfo[] fields = type.GetFields();
for (int i = 0; i < fields.Length; i++)
{
if (fields[i].Name == "name ")
{
string str = (string)fields[i].GetValue(obj);
Console.WriteLine(str);
}
}
}
------解决方案--------------------
//直接这样行了
public static void cc(Object obj)
{
Type type = obj.GetType();
FieldInfo f = type.GetField( "name ");
Console.WriteLine((string)f.GetValue(obj));
}