1

我有一个类命名Myclass为这样的覆盖ToString()

class Field
{

}

class MyClass
{
   Field propretie1 
   Field propretie2
         .
         .
         .
  Field propretie15

  public override string ToString()
  {
     StringBuilder temp = new StringBuilder(); 
     temp.Append(propretie1.ToString())
     temp.Append("|"); 
     temp.Append(propretie2.ToString())
     temp.Append("|");
         . 
         .
     temp.Append(propretie15.ToString())

     return temp.ToString();         
  }
}

我想知道是否有更好的方法来Myclass使用声明顺序来实现ToString函数的所有属性。

4

3 回答 3

2
var allProps = typeof(MyClass).GetProperties();  // or GetFields() if they are fields
Array.Sort(allProps, (x, y) => x.Name.CompareTo(y.Name));
return string.Join("|", allProps.Select(x => x.GetValue(this)));

这使用 Linq和.NET 4.5 (Visual Studio 2012)Select的重载。GetValue

于 2014-11-26T09:16:23.283 回答
2

不,除了手动编码每个功能之外,没有其他方法可以满足您的要求。反思会很容易,但是

GetFields 方法不返回特定顺序的字段,例如字母顺序或声明顺序。您的代码不得依赖于返回字段的顺序,因为该顺序会有所不同。

所以没有办法真正得到声明的顺序。不过,您可以通过自己订购来尝试按字母顺序排列。

于 2014-11-26T09:07:28.147 回答
0

.Net 提供了一个 XmlSerializer 对象,旨在为您提供对象的表示。您可以利用这一点,只需抓取文本节点并加入它们:

public override string ToString()
{
    return this.Stringify(); //calls reusable code to "stringify" any object
}

//converts an object's properties to a string of pipe delimited values
public static string Stringify<T>(this T obj)
{
    var xs = new XmlSerializer(obj.GetType());
    var doc = new XDocument();
    using (var writer = doc.CreateWriter())
    {
        xs.Serialize(writer, obj);
    }
    var s = from text in doc.XPathSelectElements("//*[./text()]") select text.Value;
    return string.Join("|", s);
}

在复杂类的属性上调用 ToString 更复杂......要做到这一点,请在这些属性上使用 XmlElement 属性,以便序列化程序知道您要输出这些属性,然后允许隐式转换为字符串,这样序列化程序就不会出错。奇怪的是,您还需要实现从字符串的隐式转换(我猜是因为序列化程序也具有反序列化的能力);但这不一定有效。非常hacky。

另一种方法是使用属性使您的子类型可序列化[Serializable],放置[XmlIgnore]任何公共属性,然后使用调用 ToString 函数的 get 方法和虚拟 set 方法创建属性(再次欺骗序列化程序)。不是很好,但它有效。

工作示例

using System;
using System.Linq;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Xml.XPath;
namespace StackOverflow
{
    public static class ObjectStringer
    {
        public static string Stringify<T>(this T obj)
        {
            var xs = new XmlSerializer(obj.GetType());
            var doc = new XDocument();
            using (var writer = doc.CreateWriter())
            {
                xs.Serialize(writer, obj);
            }
            var s = from text in doc.XPathSelectElements("//*[./text()]") select text.Value;
            return string.Join("|", s);
        }
    }
    public class Field
    {
        static int x = 0;
        int y;
        public Field()
        {
            y = ++x;
        }
        public override string ToString()
        {
            return y.ToString();
        }
        public static implicit operator String(Field f)
        {
            return f==null?null:f.ToString();
        }
        public static implicit operator Field(String s)
        {
            return s ?? "nasty hack to make serializer work";
        }
    }
    public class Demo
    {
        public string P1 { get; set; }
        public string X { get; set; } //something to show if we're pulling back results in order defined here, or if the system just goes alphabetically
        public string P2 { get; set; }
        public int P3 { get; set; }
        public DateTime P4 { get; set; }

        public Demo P5 { get; set; }
        [XmlElement(typeof(String))]
        public Field P6 { get; set; }
        [XmlElement(typeof(String))]
        public Field P7 { get; set; }

        public override string ToString()
        {
            return this.Stringify();
        }

    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Demo d = new Demo() { P1 = "test1", X = "expert mode", P2 = "test2", P3 = 3, P4 = DateTime.UtcNow, P5 = new Demo() { P1 = "baby", P2 = "ooh" },P6=new Field(),P7=new Field() };
            //d.P5 = d; //this solution's not perfect - e.g. attempt to serialize a circular loop in the object's graph
            Console.WriteLine(d.ToString());
            Console.WriteLine("done");
            Console.ReadKey();
        }
    }

}

选择

[Serializable]
public class Field
{
    static int x = 0;
    int y;

    public string DummyToString { get { return this.ToString(); }  set { /*serializer hack*/ } }
    [XmlIgnore]
    public string DontShowMe { get; set; }


    public Field()
    {
        y = ++x;
        DontShowMe = "you shouldn't see this";
    }

    public override string ToString()
    {
        return string.Format("string me on #{0}", y);
    }
}

//Demo's Field properties no longer require XmlElement attributes; i.e.:
public Field P6 { get; set; }
public Field P7 { get; set; }

注意:

  • 如果您有复杂类型的子项(例如上例中的 P5),您希望如何处理它们?它们的属性是否也应该用管道分隔(在这种情况下,您如何知道哪些属性与哪些对象相关)?
  • 应该如何处理空值 - 与空白相同(即两个管道之间没有任何内容),或者根本不输出?
  • 返回属性名称和值会更好吗 - 这样您就不会依赖顺序/您的输出对未来类定义的更改更加健壮?
  • 也许 XMLSerializer 本身更适合您的基本要求;假设您想要一种表示对象数据的稳健方式?
于 2014-11-26T21:40:22.153 回答