public string a,b,c;public void myFunction(string p)
{
      return (tmp);
}我想参数p="a"时,函数返回属性a的值,="b"时返回属性b的值,能不能做到?

解决方案 »

  1.   

    private string a,b,c;public void myFunction(string p)
    {
          this.a=p;
    }
      

  2.   

    //看错了意思   private string a,b,c;
    //传以个标志
    public void myFunction(string flag ,string p)
    {
          
    if (flag=="a")//可以用switch代替
       this.a=p;
    }
      

  3.   

    public string myFunction(string p)
    {
    System.Reflection.FieldInfo f=this.GetType().GetField(p);
    object o=null;
    if (f!=null) 
    o=f.GetValue(this);
    if (o!=null)
    return o.ToString();
    else
    return "";
    }
      

  4.   

    2楼的方法不行,可能有的属性有nnn个,写switch会死人的
      

  5.   

    经实验,jinjazz(近身剪(充电中...)) 的方法可以,但是又有问题了1、如何获得属性的数据类型?因为int,string,bool处理方法不同的
    2、对于 public string FName 这样的属性可以,但对于
       private string pFName
       public string FName
        get{
          return(pFName);
        }
        set{
           pFName = value;
        }
    这样定义的属性,System.Reflection.FieldInfo f=this.GetType().GetField(p) 取出的f就是null,这应该怎么办?
      

  6.   

    获取属性:public object myFunction2(string p)
    {
    System.Reflection.PropertyInfo f=this.GetType().GetProperty(p);
    object o=null;
    if (f!=null) 
    o=f.GetValue(this,null);
    return o;
    }
      

  7.   

    既然类型不固定就返回object了
      

  8.   

    System.Reflection.PropertyInfo f=this.GetType().GetProperty(p);运行后 f==null
      

  9.   

    确定System.Reflection.FieldInfo f1=this.GetType().GetField(p);
    System.Reflection.PropertyInfo f1=this.GetType().GetProperty(p);f1 != null 
    f2 == null
      

  10.   

    我觉得你传入的是pFName反正和属性相关的是PropertyInfo ,和成员变量相关的是FieldInfo 和方法相关的是MethodInfo
      

  11.   

    System.Reflection.FieldInfo f=this.GetType().GetField(p);
    Type t=f.GetType();解决了,谢谢
      

  12.   

    pFName是域(field),FName是属性(property),楼主不知搞清没
    类似这种运行时决定特性的问题,反射是非常有用的,本人觉得这也是c#、java这类语言非常重要的一个特点