How can I determine if an object can ToString into value or type name?

后端 未结 6 1710
青春惊慌失措
青春惊慌失措 2021-01-19 09:38

I am writing an interop between a php service and our crm. One of the things I need to do is make sure that simple types get converted ToString() for use later in a json co

6条回答
  •  礼貌的吻别
    2021-01-19 10:10

    The ToString method is a virtual one and the default implementation is defined in the Object class and simply returns the name of the type of the object:

    public virtual string ToString()
    {
      return this.GetType().ToString();
    }
    

    int for example, overrides this method to return a meaningful representation.

    What you can do is use reflection to detect whether a type overrides the ToString method like this:

    public static bool OverridesToString(Type type)
    {
        return type.GetMethod("ToString", new Type[0]).DeclaringType != typeof(object);
    }
    

    If it does, there is a very good chance that the ToString method would return something meaningful.

提交回复
热议问题