| Severity | Error |
| Reported by | PostSharp |
| Message | Type of field "<Field>" is invalid. Valid types for fields annotated with [ImportMember] are: Delegate, Event<T>, Property<TValue>, Property<TValue,TIndex>. |
Cause
An aspect imports a member of its target class with a field annotated with ImportMemberAttribute. At run time, PostSharp does not copy the value of the member into this field: it assigns delegates that invoke the member. The type of the field therefore tells PostSharp which kind of member to import:
- a delegate type imports a method;
- Property<TValue> imports a property, and Property<TValue, TIndex> an indexer;
- Event<TDelegate> imports an event.
PostSharp reports LA0074 when the field has any other type, typically the type of the imported property itself.
In the following example, the [TraceCreation] aspect imports the Name property of Customer into a field of type string.
using System;
using PostSharp.Aspects;
using PostSharp.Aspects.Advices;
using PostSharp.Serialization;
namespace Errors.LA0074_Error;
[PSerializable]
public class TraceCreationAttribute : InstanceLevelAspect
{
// A string field cannot receive the Name property of the target class.
[ImportMember( "Name", IsRequired = true )]
public string? Name;
public override void RuntimeInitializeInstance()
{
Console.WriteLine( $"Created {this.Name}" );
}
}
[TraceCreation]
public class Customer
{
public string Name { get; set; } = "Alice";
}
public static class Program
{
public static void Main()
{
_ = new Customer();
}
}
error LA0074: LA0074_Error.cs(13,20): Type of field "Errors.LA0074_Error.TraceCreationAttribute.Name" is invalid. Valid types for fields annotated with [ImportMember] are: Delegate, Event<T>, Property<TValue>, Property<TValue,TIndex>.
Resolution
Change the type of the field to the type that matches the kind of the imported member: a delegate with the signature of the method, Property<TValue> or Property<TValue, TIndex> for a property or an indexer, or Event<TDelegate> for an event. Then access the member through the delegates of the field, for example Get.
In the following example, the field has the type Property<string>, and the aspect calls its Get delegate.
using System;
using PostSharp.Aspects;
using PostSharp.Aspects.Advices;
using PostSharp.Serialization;
namespace Errors.LA0074_Fixed;
[PSerializable]
public class TraceCreationAttribute : InstanceLevelAspect
{
// A Property<string> field receives the accessors of the Name property.
[ImportMember( "Name", IsRequired = true )]
public Property<string>? Name;
public override void RuntimeInitializeInstance()
{
Console.WriteLine( $"Created {this.Name!.Get()}" );
}
}
[TraceCreation]
public class Customer
{
public string Name { get; set; } = "Alice";
}
public static class Program
{
public static void Main()
{
_ = new Customer();
}
}
Created Alice
See Also
Reference
ImportMemberAttribute
Property<TValue>
Event<TDelegate>
Other Resources