mardi 5 juillet 2022

Get type of decorated parameter in attribute

Having an attribute like this,

[AttributeUsage(AttributeTargets.Parameter)]
public class MyParamAttribute : Attribute { .. }

is there a way to get the type of the decorated parameter in the attribute implementation?

public void MyMethod([MyParam] string param) { .. }
[AttributeUsage(AttributeTargets.Parameter)]
public class MyParamAttribute : Attribute
{
    public Type ParamType => ...?
}

I wonder if there's a subtle way to get the type of the parameter apart from passing it directly by constructor.

[AttributeUsage(AttributeTargets.Parameter)]
public class MyParamAttribute : Attribute
{
    public MyParamAttribute(Type type) => ParamType = type;

    public Type ParamType { get; }
}

// ...
public void MyMethod([MyParam(typeof(string))] string param) { .. }

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire