Metaprogramming in C #: ToString Automatic Method

I have several classes that serve only for storing data. for instance

public class EntityAdresse : IEntityADRESSE
{
    public string Name1 { get; set; }
    public string Strasse { get; set; }
    public string Plz { get; set; }
    public string Ort { get; set; }
    public string NatelD { get; set; }
    public string Mail { get; set; }
    public int Id_anrede { get; set; }
    public string Telefon { get; set; }
    public int Id_adr { get; set; }
    public int Cis_adr { get; set; }
}

This adress. As I said, it contains only data. There are no methods (I know that the interface does not make sense here ...)

Now I need to implement ToString for all of these Entity-Classes, and there are many.

My question is: is there a metaprogramming function in C # that automatically generates these tostring methods? I do not want to write boiler plate code for each of these classes.

Alternatively, I could write a perl or python script to generate the code. But I prefer to do it directly in C #.

+5
source share
4 answers

, . , :

public override string ToString() 
{
    PropertyDescriptorCollection coll = TypeDescriptor.GetProperties(this);
    StringBuilder builder = new StringBuilder();
    foreach(PropertyDescriptor pd in coll)
    {
        builder.Append(string.Format("{0} : {1}", pd.Name , pd.GetValue(this).ToString()));
    }
    return builder.ToString();
}
+7

. :

  public class EntityBase
  {
      public override string ToString()
      {
          StringBuilder sb = new StringBuilder();

          foreach ( var property in this.GetType().GetProperties() )
          {
              sb.Append( property.GetValue( this, null ) );
          }

          return sb.ToString();
      } 
  }

  public class TheEntity : EntityBase
  {
      public string Foo { get; set; }
      public string Bar { get; set; }
  }

, , .

, , , .

+3

, , , , Expression , , .

:

Func<T,string> GenerateToString<T>()

- :

public class EntityAdresse : IEntityADRESSE
{
    private static readonly Func<EntityAdresse,string> s_ToString=Generator.GenerateToString<EntityAdresse>();

    public string Name1 { get; set; }
    public string Strasse { get; set; }
    public string Plz { get; set; }
    public string Ort { get; set; }
    public string NatelD { get; set; }
    public string Mail { get; set; }
    public int Id_anrede { get; set; }
    public string Telefon { get; set; }
    public int Id_adr { get; set; }
    public int Cis_adr { get; set; }

    public override ToString()
    {
       return s_ToString(this);
    }
}

GenerateToString. Expression , , , .

, .

+1

There is an open source StatePrinter framework for creating ToString automatically . It is very customizable, so it should suit your needs. Introspection code can be found on Introspection

0
source

All Articles