2014-01-23 27 views
0

我有一个类的System.Reflection用法

class ABC 
{ 
    Public int one = 10; 
    Public String two = "123"; 
    public override string ToString() 
    { 
    } 
} 

我的问题我想在类的字符串“ABC”字段的信息/值当过,我将创建一个类的对象。例如:

Public Class Test 
{ 
    public static void Main() 
    { 
     ABC a = new ABC(); 
     a.ToString(); 
    } 
} 

现在我在这里创建一个对象类“ABC”的,那么我想重写的ToString()的方法来获得字符串ABC类的所有字段的值。

+3

为什么不干脆重写'ABC.ToString()'返回你想要什么? – Sean

+0

@Sean,手动返回“所需属性”不能很好地扩展。 –

+0

@AndreiV - 谁说要保留他们? – Sean

回答

0

不知道这是你的意思;

public override ToString() 
{ 
    return string.Format("one: {1}{0}two: {2}", Environment.NewLine(), one, two); 
} 
+2

我认为他想要一个使用反射的一般方法。 –

0

您既可以使用属性检索字符串,或覆盖ToString(),两者都显示:

public class ABC 
{ 
    private Int32 _one = 10; 
    public Int32 One { get { return _one; } } 
    private String _two = "123"; 
    public String Two { get { return _two; } } 

    protected override ToString() 
    { 
     return _two; 
    } 
} 
+2

我不认为这个问题重写'ToString'。我认为问题是“我如何使用反射来枚举类的所有域,然后从它们中创建一个字符串” –

1
public override string ToString() 
{ 
    Dictionary<string, string> fieldValues = new Dictionary<string, string>(); 
    var fields = this.GetType().GetFields(); 

    foreach (var field in fields) 
    { 
     fieldValues[field.Name] = field.GetValue(this).ToString(); 
    } 

    return string.Join(", ", fieldValues.Select(x => string.Format("{0}: {1}", x.Key, x.Value))); 
} 
+0

FieldInfo不会给我值,我可以从propertyInfo –

0

这应做到:

public override string ToString() { 
    string s = ""; 
    foreach(FieldInfo f in this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public)) { 
     s += f.Name + "=" + f.GetValue(this).ToString() + "\r\n"; 
    } 
    return s; 
} 

BindingFlags.Public反映只有公众成员。如果你想要私人会员,也可以使用BindingFlags.Private标志。
您可以在对象初始化时使用this.GetType().GetFields(),仅调用一次。

这也适用于框架2。
将其更改为您的需要。

0

所以,在这里,它是:

public class ABC 
    { 
     public int one; 
     public string two; 
     public int three; 

     public override string ToString() 
     { 
      string names = String.Empty; 
      System.Reflection.FieldInfo[] infos = this.GetType().GetFields(); 

      foreach (System.Reflection.MemberInfo inf in infos) 
      { 
       if (names == String.Empty) 
       { 
        names = inf.Name; 
       } 
       else 
       { 
        names += ';' + inf.Name; 
       } 
      } 

      return names; 
     } 
    } 

享受!

0

而不是使用反射,你可以使用任何以下两种方法之一:

1:在这里,你可以序列化您的类对象的JSON对象这将是更具可读性:

public override string ToString() 
    { 

     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ABC)); 
     string str; 
     using (MemoryStream stream = new MemoryStream()) 
     { 
      serializer.WriteObject(stream, this); 
      stream.Position = 0; 
      using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8)) 
      { 

       str = streamReader.ReadToEnd(); 
      } 
     } 

     return str; 
} 

2 :在这里,你可以序列化类对象到XML可以利用一些别的地方:

public override string ToString() 
    { 

     XmlSerializer s = new XmlSerializer(typeof(ABC)); 
     StringBuilder sb = new StringBuilder(); 
     var xtw = XmlTextWriter.Create(sb); 
     s.Serialize 
      (xtw, this); 

     return sb.ToString(); 
} 
0

终于得到解决我的问题:)

using System; 
using System.Reflection; 
using System.IO; 
using System.Collections.Generic; 
using System.Text; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     MyClass mC= new MyClass(); 
     string result = mC.ToString(); 
    } 
} 

class MyClass 
{ 
    string someValue = "One"; 
    int someValue1 = -1; 
    bool someValue2 = false; 
    float someValue3 = 2.2f; 

    public string SomeValue 
    { 
     get{ return this.someValue;} 
    } 

    public int SomeValue1 
    { 
     get { return this.someValue1; } 
    } 

    public bool SomeValue2 
    { 
     get { return this.someValue2; } 
    } 

    public float SomeValue3 
    { 
     get { return this.someValue3; } 
    } 

    public override string ToString() 
    { 
     string result = string.Empty; 
     Type type = this.GetType(); 
     PropertyInfo [] pInfo = type.GetProperties(); 

     for (int i = 0; i <= pInfo.Length-1; i++) 
     { 
      Type internalType = this.GetType(); 
      PropertyInfo pInfoObject = internalType.GetProperty(pInfo[i].Name); 
      object value = pInfoObject.GetValue(this,null); 
      result += pInfo[i].Name + " : " + value.ToString() + System.Environment.NewLine; 
     } 
     return result; 
    } 
} 
0

下面是一个其他的解决办法,如果我们使用静态字段和fieldsInfo:

class ReflectionTest 
{ 
    public static int Height = 2; 
    public static int Width = 10; 
    public static int Weight = 12; 
    public static string Name = "Got It"; 

    public override string ToString() 
    { 
     string result = string.Empty; 
     Type type = typeof(ReflectionTest); 
     FieldInfo[] fields = type.GetFields(); 
     foreach (var field in fields) 
     { 
      string name = field.Name; 
      object temp = field.GetValue(null); 
      result += "Name:" + name + ":" + temp.ToString() + System.Environment.NewLine; 
     } 
     return result; 
    } 

}