开发者

Is it possible to use dynamic to provide generic ToString override for object

I'm a little tired of writing ToString methods for my dto classes. It occurred to me that it might be possible to convert a dto to a dynamic type and then use the linq aggregate method and StringBuilder to construct a standard string for logging type output. Unfort开发者_如何学JAVAunately I'm only just starting to learn about dynamic types in C# so I'm a little bit stuck right now. Any suggestions?


Following implementation uses an extention method on object and using reflection and linq creates a string of all property names and values. Again, collections/arrays have to be handled differently.

CODE EDIT Removing all the related code and only keeping the extention required.

public static string ToStringLinq(this object o)
{
    return o.GetType().FullName 
        + Environment.NewLine 
        + string.Join(Environment.NewLine, (from p in o.GetType().GetProperties()
                                            select string.Format("{0}{1}{2}", p.Name, ':', p.GetValue(o, null))));
}

Usage

 AnyClass instance = new AnyClass();
 string toString = instance.ToStringLinq();


If using LINQ to SQL or Entity Framework, you have to look at SqlMetal or the EF T4 templates to generate custom code; you can create your own base class and have all your entities inherit from this base class, which has this method.

Or create an extension method to extend your classes and this extension method uses reflection to do what you want.

HTH.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜