【发布时间】:2014-02-14 00:33:23
【问题描述】:
我有课
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 类的所有字段值。
作为解决方案,这对我有用:
**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;
}
}
【问题讨论】:
-
为什么不直接覆盖
ABC.ToString()来返回你想要的? -
@Sean,手动返回“所需属性”不能很好地扩展。
-
@AndreiV - 谁说过要留住他们?
-
@AndreiV 可以说每次都不是反射和连接字符串
-
@Sean,那我很困惑。他确实说他想覆盖
ToString()方法。有两种可能性:手动编写包含“属性名称/属性值”的“键/值”对或使用反射动态获取属性及其值。我错了吗?你想到了什么?
标签: c# reflection