| Severity | Error |
| Reported by | PostSharp |
| Message | Cannot import a member into field "<Field>": the advice "<Advice>" has a null or empty array of member names. Specify the name of at least one member to import. |
Cause
An aspect imports a member of its target class with a field annotated with ImportMemberAttribute. PostSharp finds the member by the names that the constructor of the attribute receives, in the MemberNames property, and does not use the name of the field. When this array is empty or null, PostSharp does not know which member to import and reports LA0162 on the field.
The usual cause is the attribute without arguments, [ImportMember], which C# accepts because the constructor takes a params array. <Advice> is the type of the advice, ImportMemberAttribute.
In the following example, the [TraceCreation] aspect imports a member into its Name field without naming it.
using System;
using PostSharp.Aspects;
using PostSharp.Aspects.Advices;
using PostSharp.Serialization;
namespace Errors.LA0162_Error;
[PSerializable]
public class TraceCreationAttribute : InstanceLevelAspect
{
// The attribute does not say which member of the target class to import.
[ImportMember]
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();
}
}
error LA0162: LA0162_Error.cs(13,30): Cannot import a member into field "Errors.LA0162_Error.TraceCreationAttribute.Name": the advice "PostSharp.Aspects.Advices.ImportMemberAttribute" has a null or empty array of member names. Specify the name of at least one member to import.
Resolution
Pass the name of the member to import to the constructor of ImportMemberAttribute, for example [ImportMember( "Name" )]. You can also pass several possible names, in order of precedence.
In the following example, the aspect imports the Name property of Customer.
using System;
using PostSharp.Aspects;
using PostSharp.Aspects.Advices;
using PostSharp.Serialization;
namespace Errors.LA0162_Fixed;
[PSerializable]
public class TraceCreationAttribute : InstanceLevelAspect
{
// The attribute names the property of the target class to import.
[ImportMember( "Name" )]
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>
Other Resources