日期:2014-05-19  浏览次数:20868 次

struct结构问题
两个结构
struct   p1
{
    public   int   a;
}
struct   p2
{
    public   string   b;
}
默认过程:
private   void   setp1(ref   p1   p)
{
    random   rnd=new   random();
    p.a=rnd.next(10000);
}
private   void   setp2(ref   p2   p)
{
    random   rnd=new   random();
    p.b=rnd.next(10000).tostring();
}
我想有没有办法把两个过程集成起来?????????????????????问问能不能实现
private   setp(ref   type   p)
{
      反射p的字段并且赋值
}

------解决方案--------------------

struct p1
{
public int a;
}
struct p2
{
public string b;
}


private object setp(object o)
{
System.Random rnd = new System.Random();
FieldInfo[] fields = o.GetType().GetFields();
Type ht = o.GetType();
if (fields[0].FieldType.ToString() == "System.Int32 ")
{
object oo = new object();
oo = rnd.Next(10000);
fields[0].SetValue(o, oo);
}
else if (fields[0].FieldType.ToString() == "System.String ")
{
object oo = new object();
oo = rnd.Next(10000).ToString();
fields[0].SetValue(o, oo);
}
return o;
}

private void button1_Click(object sender, EventArgs e)
{
p1 p = new p1();
object o = setp(p);
p = (p1)o;
MessageBox.Show(p.a.ToString());
}

private void button2_Click(object sender, EventArgs e)
{
p2 p = new p2();
object o = setp(p);
p = (p2)o;
MessageBox.Show(p.b.ToString());
}
------解决方案--------------------