0

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?

2 Answers 2

4

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...

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that makes alot of sense.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.