Home > Software design >  Get attribute info info from parameter of type extension methode ? any other appraoch?
Get attribute info info from parameter of type extension methode ? any other appraoch?

Time:01-21

there's any way to get attribute info from parameter of type extension methode ? For example :

I have an Attribute like this :

 [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
    public class MyAttribute: Attribute 
    {
        public MyAttribute(string _mystring)
        {
            myString= _mystring;
        }

        public string myString{ get; set; }
    }

So,I have a property like this :

  [MyAttribute("TestInt")]
        public int MyInt;

and an extension methode like this :

public static void Execute(ref this int t)
        {
          //Get Attribute info here
          Console.WriteLine(t);
        }

and I wanna use it like this

MyInt.Execute();

Can i get the Attribute info in the Execute methode ?

CodePudding user response:

The short answer is "no".

An int of ref int is just that value/reference - it doesn't carry with it the metadata context to understand things like attributes.

The only way I can think of for conveying that would be "expressions"; consider:

var obj = new Foo { MyInt = 42 };
SomeUtil.Execute(() => obj.MyInt);

where Execute is:

static class SomeUtil
{
    public static void Execute(Expression<Func<int>> t)
    {
        // investigate the attributes (only supports very simple scenarios currently)
        if (t.Body is MemberExpression me)
        {
            foreach (var attrib in me.Member.GetCustomAttributes<MyAttribute>())
            {
                Console.WriteLine(attrib.myString);
            }
        }

        // show the value
        Console.WriteLine(t.Compile()());
    }
}

This will work, but is very inefficient - it involves building an expression tree at the call-site each time, and then investigating that expression tree. Plus it also materializes the attribute instances each time. There are scenarios where this might be OK, but in the general case: definitely worth avoiding.

  • Related