首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >System.Reflection使用

System.Reflection使用
EN

Stack Overflow用户
提问于 2014-01-23 12:44:22
回答 8查看 384关注 0票数 0

我有个课

代码语言:javascript
运行
复制
class ABC
{
    Public int one = 10;
    Public String two = "123";
  public override string ToString()
   {
   }
}

我的问题--我想在"ABC“类的字符串中获取字段信息/值,当我要创建该类的一个对象时。例如:

代码语言:javascript
运行
复制
Public Class Test
{
    public static void Main()
    {
        ABC a = new ABC();
        a.ToString();
    }
}

现在我创建一个" ABC“类的对象a,然后重写ToString()的方法,以获得一个字符串中的ABC类的所有字段值。

作为解决方案--这对我有用:

代码语言:javascript
运行
复制
**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;
    }

}
EN

回答 8

Stack Overflow用户

发布于 2014-01-23 12:50:13

代码语言:javascript
运行
复制
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)));
}
票数 1
EN

Stack Overflow用户

发布于 2014-01-23 12:48:28

不知道这是不是你的意思;

代码语言:javascript
运行
复制
public override ToString() 
{
    return string.Format("one: {1}{0}two: {2}", Environment.NewLine(), one, two);
}
票数 0
EN

Stack Overflow用户

发布于 2014-01-23 12:48:37

您可以使用属性检索字符串,也可以重写ToString(),这两者都如图所示:

代码语言:javascript
运行
复制
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;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21308548

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档