SharpCrafters Forum – Aspect, allowing to override object methods ToString, Equals, GetHashCode

SharpCrafters Support Forum

        


Aspect, allowing to override object methods... Expand / Collapse
Author
Message
Posted 3/2/2010 6:42:09 PM


Community Member
For my data transfer objects I would like to have possibility to override ToString() method in one way - by exposing public properties. The same for Equals method, by comparing public properties.

I wrote custom attribute for ToString implementation by inheriting from ImplementMethodAspect, usage is like this:


 public class TestDummy
 {
   public string Name { get; set; }
   public string Surname { get; set; }
   [ImplementToString]
   public override string ToString()
   {
     return String.Empty;
   }
 }


but I still have to write ToString method in each of my classes.

Is there any way I can do like this:


 [AddToStringImplementation]
 public class TestDummy
 {
   public string Name { get; set; }
   public string Surname { get; set; }
 }

?

I tried to implement AddToStringImplementationAttribute by inheriting from CompositionAspect, but without luck:


 public interface IToStringable
 {
   string ToString();
 }

 [Serializable]
 public class AddToStringAttribute : CompositionAspect
 {
   public override object CreateImplementationObject(InstanceBoundLaosEventArgs eventArgs)
   {
    return new ToStringableImplementation();
   }



   public override Type GetPublicInterface(Type containerType)
   {
     return typeof (IToStringable);
   }

   public override CompositionAspectOptions GetOptions()
   {
     return CompositionAspectOptions.GenerateImplementationAccessor;
   }
 }

 public class ToStringableImplementation : IToStringable
 {
   #region IToStringable Members

  string IToStringable.ToString()
   {
     return "To string was called!!!";
   }

   #endregion
 }


When I call ToString method for object of a class, marked with AddToStringAttribute, method from ToStringableImplementation is not called (which is really correct, it is called only if I cast the object to IToStringable before).

Is there any way to override object basic methods with PostSharp attribute?
Post #4064
Posted 3/5/2010 12:39:35 PM


Gael Fraiteur

SharpCrafters
Yes: you should use InstanceLevelAspect with a MemberIntroduction.


class ImplementToStringAspect : InstanceLevelAspect
{
 [IntroduceMember]
 public override string ToString()
 {
  return this.Instance.GetType().FullName;
 }
}
Post #4081
Posted 3/12/2010 11:02:16 AM


Community Member
Gael, thanks a lot!

This aspect is new in PostSharp 2.0, right? Couldn't find it in 1.5.
Post #4155
Posted 3/12/2010 11:03:14 AM


Gael Fraiteur

SharpCrafters
Right, that's a new feature of 2.0 (commercial edition required).
Post #4156
« Prev Topic | Next Topic »


All times are GMT +1:00, Time now is 11:44am

Powered By InstantForum.NET v4.1.4 © 2010
Execution: 2.075. 8 queries. Compression Disabled.