Derek
Derek

Reputation: 8630

Declare Custom Attribute that create a new object

I'm not sure what i am trying to do is actually possible.

I want to create a new Custom Attribute where by when the attribute is declared the user creates a new object.

I'm looking at Lucene.Net and i want to add a custom attribute to my class property, so i can determine multiple parameters.

Here is my Custom Attribute, It takes in a Lucene.Net Field object :-

[AttributeUsage(AttributeTargets.Property)]
    public class PropertyAnalysed : Attribute
    {
        public Field Field;

        public PropertyAnalysed(Field field)
        {
            this.Field = field;
        }
    }

When I declare the custom attribute on property, I want to do the following :-

 [LuceneIndex("SampleIndex")]
    public class SampleClass
    {
        [LuceneProperty]
        [PropertyAnalysed(new Field("","",Field.Store.YES, Field.Index.ANALYZED))]
        public int Id { get; set; }
    }

However, i get the following error :-

"An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type"

Can anyone help on what i can do?

Upvotes: 0

Views: 554

Answers (2)

David
David

Reputation: 10708

Like the error says, you can only use compile-time constants - which is to say, only primitives you can declare without use of the new keyword. Since Attributes are class-level, they can't be passed anything which requires a new statement.

Attribute constructors, similarly, won't let you declare a parameter which would be invalid to pass. Attributes also can't be generic - hence the explicit mention of typeof(...) statements being allowed.

Your best bet is to have some way of parsing a Field from a given string, and passing a string into your attribute. If that's not an option, you could also specify a type and string which represent the class and static member you want looked up, and use reflection to find that property by name.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500145

The simplest approach would be to take several separate parameters, and create the Field instance based on those parameters. You can only configure attributes with compile-time constants, and new Field(...) isn't a compile-time constant.

You may not need all the parameters anyway - for example, Field.Index.ANALYZED sounds like it will be pointless in a PropertyAnalysed attribute, as surely all fields would have that...

Upvotes: 4

Related Questions