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

前端 未结 2 812
失恋的感觉
失恋的感觉 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: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 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.

提交回复
热议问题