如何使用Class对象的值打印字段名称? [英] how to print Field name with value of a Class object?

查看:47
本文介绍了如何使用Class对象的值打印字段名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我需要使用值打印类字段或属性名称,而不使用反射或string.join方法。



例如。



 protected void Button1_Click(object sender,EventArgs e)
{
List< EmployeeInfo> obj = new List< EmployeeInfo>();
obj.Add(new EmployeeInfo {eid = 123});
obj.Add(new EmployeeInfo {ename =abc});

Response.Write(obj.ToString()); //输出必须是=> ename =abc,eid = 123
}

公共类EmployeeInfo
{
public string ename;
public int eid;
}



需要使用属性名称和值自动生成如下结果:



ename =abc,eid = 123



需要以良好的性能和简单的方式获得结果。

解决方案

1.您应该在 EmployeeInfo 类中覆盖方法 ToString()

  public   class  EmployeeInfo 
{
public string ename;
public int eid;

public 覆盖 string ToString()
{
return string .Format( ename = \{0} \,eid = {1}
.ename,
.eid);
}
}



2.您应该优化/简化 Button1_Click 中的代码这个:

 受保护  void  Button1_Click(  object  sender,EventArgs e)
{
EmployeeInfo obj = new EmployeeInfo {ename = abc,eid = 123 };
Response.Write(obj.ToString());
}


手动工作很简单,如果string.format太长,你可以使用StringBuilder.Append。



另外,您可以尝试实现ISerializable接口(我不确定您将获得的输出的确切格式,但您肯定会获得包含所有属性的字符串。

hi, In C#, I need to print a class field or property name with value without using reflection or string.join method.

For eg.

protected void Button1_Click(object sender, EventArgs e)
    {
        List<EmployeeInfo> obj = new List<EmployeeInfo>();
        obj.Add(new EmployeeInfo { eid = 123 });
        obj.Add(new EmployeeInfo { ename = "abc" });

        Response.Write(obj.ToString()); // output must be  => ename ="abc" , eid = 123
    }

    public class EmployeeInfo
    {
        public string ename;
        public int eid;
    }


It need to be resulted as follows automatically with property name and value :

ename ="abc" , eid = 123

It need to be resulted with good performance and simple way.

解决方案

1.You should overwrite the method ToString() in your EmployeeInfo class:

public class EmployeeInfo
    {
        public string ename;
        public int eid;
        
        public override string ToString()
        {
            return string.Format("ename = \"{0}\" , eid = {1}",
                this.ename,
                this.eid);
        }
    }


2.You should refine/simplify the code from Button1_Click like this:

protected void Button1_Click(object sender, EventArgs e)
    {
        EmployeeInfo obj = new EmployeeInfo { ename= "abc", eid = 123 };
        Response.Write(obj.ToString()); 
    }


Manual work is simple, you can use StringBuilder.Append if string.format would get too long.

Also, you could try to implement ISerializable interface (I'm not sure of the exact format of the output you would get, but you would definitely get a string with all the properties.


这篇关于如何使用Class对象的值打印字段名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆