有没有办法告诉如果一个对象在C#中实现明确的ToString [英] Is there a way to tell if an object has implemented ToString explicitly in c#

查看:237
本文介绍了有没有办法告诉如果一个对象在C#中实现明确的ToString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想日志关于我的一些代码对象和类的状态信息。并非所有的类或库用序列化来实现。所以我使用的属性思考写出来的状态的XML文档。不过,我像内置的类一些对象(如字符串,日期时间,数字等)有打印出的类以有意义的方式值的ToString函数是一个挑战。但是,对于其他类,调用toString只是用继承的基础的ToString吐出对象类型(例如字典)的名称。在这种情况下,我想递归地检查到类中的属性。

I am trying to log information about the state of some objects and classes in my code. Not all the classes or libraries were implemented with Serialization. So I am using Reflection on the Properties to write out an XML document of the state. However, I have a challenge in that some objects like builtin Classes (ie Strings, DateTime, Numbers etc...) have a ToString function that prints out the value of the class in a meaningful way. But for other classes, calling ToString just uses the inherited base ToString to spit out the name of the object type (For example a Dictionary). In that case I want to recursively examine to properties inside that class.

所以,如果有人能帮助我与反思要么找出是否有对物业实施的ToString我看这是不是基本的方法或指出使用的GetValue检索集合属性我将不胜感激的正确方法。

So if anyone can help me with reflection to either figure out if there is a ToString implemented on the property I'm looking at that isn't the base method OR to point out the proper way of using GetValue to retrieve collection properties I would appreciate it.

Ĵ

推荐答案

要确定一个方法是否覆盖默认的的ToString()检查 MethodInfo.DeclaringType 像这样:

To determine whether a method has overridden the default .ToString() check MethodInfo.DeclaringType like so:

void Main()
{
    Console.WriteLine(typeof(MyClass).GetMethod("ToString").DeclaringType != typeof(object));
    Console.WriteLine(typeof(MyOtherClass).GetMethod("ToString").DeclaringType != typeof(object));
}

class MyClass 
{
    public override string ToString() { return ""; }
}

class MyOtherClass {
}

打印出来:

True
False

这篇关于有没有办法告诉如果一个对象在C#中实现明确的ToString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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