我有个课
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“类的对象a,然后重写ToString()的方法,以获得一个字符串中的ABC类的所有字段值。
作为解决方案--这对我有用:
**Here is an other solution if we use static fields and 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;
}
}
发布于 2014-01-23 12:50:13
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)));
}
发布于 2014-01-23 12:48:28
不知道这是不是你的意思;
public override ToString()
{
return string.Format("one: {1}{0}two: {2}", Environment.NewLine(), one, two);
}
发布于 2014-01-23 12:48:37
您可以使用属性检索字符串,也可以重写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;
}
}
https://stackoverflow.com/questions/21308548
复制相似问题