|
|
|
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?
|
|
|
|
|
Gael Fraiteur
SharpCrafters
|
|
Yes: you should use InstanceLevelAspect with a MemberIntroduction.
class ImplementToStringAspect : InstanceLevelAspect { [IntroduceMember] public override string ToString() { return this.Instance.GetType().FullName; } }
|
|
|
|
|
Community Member
|
|
Gael, thanks a lot!
This aspect is new in PostSharp 2.0, right? Couldn't find it in 1.5.
|
|
|
|
|
Gael Fraiteur
SharpCrafters
|
|
|
Right, that's a new feature of 2.0 (commercial edition required).
|
|
|
|