How do you put a Func in a C# attribute (annotation)?

前端 未结 2 798
失恋的感觉
失恋的感觉 2021-01-03 20:55

I have a C# annotation which is :

[AttributeUsage(AttributeTargets.Method)]
public class OperationInfo : System.Attribute {
    public enum VisibilityType {
         


        
相关标签:
2条回答
  • 2021-01-03 21:19

    From the C# spec:

    17.1.3 Attribute parameter types

    The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:

    · One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort.

    · The type object.

    · The type System.Type.

    · An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (§17.2).

    · Single-dimensional arrays of the above types.

    0 讨论(0)
  • 2021-01-03 21:24

    I don't think it is possible, c# only allows you to use Attributes with constant values only.

    One way of doing this would be to create a class instead of a func, and then you pass the type of that class into the attribute. You'd then need to instantiate it with reflection and execute a method in it.

    So an example would be:

    public interface IDoStuff
    {
        IList<string> Execute();
    }
    

    then your attribute would take a type instead of a Func

    public OperationInfo(VisibilityType v, string title, Type type)
    {
       ///...
    }
    

    you then would create a class that implements your interface and pass it into the attribute. Although this would mean that (at least initially, and without knowing your problem) you will need to create a new class every time you want to return different results.

    0 讨论(0)
提交回复
热议问题